/**
 * Transport Tracking Types for LocalGreenChain
 * Seed-to-Seed transport event tracking with blockchain integration
 */

// Transport Location with full traceability
export interface TransportLocation {
  latitude: number;
  longitude: number;
  address?: string;
  city?: string;
  region?: string;
  country?: string;
  postalCode?: string;
  locationType: 'farm' | 'greenhouse' | 'vertical_farm' | 'warehouse' | 'hub' | 'market' | 'consumer' | 'seed_bank' | 'other';
  facilityId?: string;
  facilityName?: string;
}

// Transport method definitions
export type TransportMethod =
  | 'walking'
  | 'bicycle'
  | 'electric_vehicle'
  | 'hybrid_vehicle'
  | 'gasoline_vehicle'
  | 'diesel_truck'
  | 'electric_truck'
  | 'refrigerated_truck'
  | 'rail'
  | 'ship'
  | 'air'
  | 'drone'
  | 'local_delivery'
  | 'customer_pickup';

// Carbon emission factors (kg CO2 per km per kg of cargo)
export const CARBON_FACTORS: Record<TransportMethod, number> = {
  walking: 0,
  bicycle: 0,
  electric_vehicle: 0.02,
  hybrid_vehicle: 0.08,
  gasoline_vehicle: 0.12,
  diesel_truck: 0.15,
  electric_truck: 0.03,
  refrigerated_truck: 0.25,
  rail: 0.01,
  ship: 0.008,
  air: 0.5,
  drone: 0.01,
  local_delivery: 0.05,
  customer_pickup: 0.1
};

// Plant lifecycle stages
export type PlantStage =
  | 'seed'
  | 'germinating'
  | 'seedling'
  | 'vegetative'
  | 'flowering'
  | 'fruiting'
  | 'mature'
  | 'harvesting'
  | 'post_harvest'
  | 'seed_saving';

// Environmental conditions during transport
export interface TransportEnvironment {
  temperatureMin: number;
  temperatureMax: number;
  temperatureAvg: number;
  humidityMin: number;
  humidityMax: number;
  humidityAvg: number;
  lightExposure: 'dark' | 'low' | 'ambient' | 'bright';
  shockEvents?: number;
  handlingNotes?: string;
}

// Temperature requirements for produce
export interface TemperatureRange {
  min: number;
  max: number;
  optimal: number;
  unit: 'celsius' | 'fahrenheit';
}

// Seed storage conditions
export interface SeedStorageConditions {
  temperature: number;
  humidity: number;
  lightExposure: 'dark' | 'minimal';
  containerType: 'envelope' | 'jar' | 'vacuum_sealed' | 'moisture_proof' | 'seed_vault';
  desiccant: boolean;
  estimatedViability: number; // years
}

// Base transport event
export interface BaseTransportEvent {
  id: string;
  timestamp: string;
  eventType: TransportEventType;

  // Locations
  fromLocation: TransportLocation;
  toLocation: TransportLocation;

  // Distance and duration
  distanceKm: number;
  durationMinutes: number;

  // Environmental impact
  transportMethod: TransportMethod;
  carbonFootprintKg: number;

  // Verification
  senderId: string;
  receiverId: string;
  senderSignature?: string;
  receiverSignature?: string;
  verifierSignature?: string;

  // Status
  status: 'pending' | 'in_transit' | 'delivered' | 'verified' | 'disputed';

  // Metadata
  notes?: string;
  photos?: string[];
  documents?: string[];
}

export type TransportEventType =
  | 'seed_acquisition'
  | 'planting'
  | 'growing_transport'
  | 'harvest'
  | 'processing'
  | 'distribution'
  | 'consumer_delivery'
  | 'seed_saving'
  | 'seed_sharing';

// Seed Acquisition Transport Event
export interface SeedAcquisitionEvent extends BaseTransportEvent {
  eventType: 'seed_acquisition';

  seedBatchId: string;
  sourceType: 'seed_bank' | 'previous_harvest' | 'trade' | 'purchase' | 'wild_collected' | 'gift';

  // Seed details
  species: string;
  variety?: string;
  quantity: number;
  quantityUnit: 'seeds' | 'grams' | 'ounces' | 'packets';

  // Lineage
  geneticLineageId?: string;
  parentPlantIds?: string[];
  generation: number;

  // Quality
  germinationRate?: number;
  purityPercentage?: number;
  harvestDate?: string;
  expirationDate?: string;

  // Certifications
  certifications?: ('organic' | 'non_gmo' | 'heirloom' | 'certified_seed' | 'biodynamic')[];
  certificationDocuments?: string[];
}

// Planting Event
export interface PlantingEvent extends BaseTransportEvent {
  eventType: 'planting';

  seedBatchId: string;
  plantIds: string[]; // New plant IDs created

  plantingMethod: 'direct_sow' | 'transplant' | 'indoor_start' | 'hydroponic' | 'aeroponic';
  sowingDepth?: number; // mm
  spacing?: number; // cm
  quantityPlanted: number;

  growingEnvironment: 'outdoor' | 'greenhouse' | 'indoor' | 'vertical_farm';
  expectedHarvestDate?: string;
}

// Growing Transport Event (transplanting, moving plants)
export interface GrowingTransportEvent extends BaseTransportEvent {
  eventType: 'growing_transport';

  plantIds: string[];
  reason: 'transplant' | 'relocation' | 'hardening_off' | 'seasonal_move' | 'upgrade_facility';

  plantStage: PlantStage;
  handlingMethod: 'bare_root' | 'potted' | 'root_ball' | 'hydroponic_transfer' | 'aeroponic_transfer';

  rootDisturbance: 'none' | 'minimal' | 'moderate' | 'significant';
  acclimatizationRequired: boolean;
  acclimatizationDays?: number;
}

// Harvest Event
export interface HarvestEvent extends BaseTransportEvent {
  eventType: 'harvest';

  plantIds: string[];
  harvestBatchId: string;

  harvestType: 'full' | 'partial' | 'continuous' | 'selective';
  produceType: string; // e.g., "tomatoes", "lettuce heads", "basil leaves"

  // Quantities
  grossWeight: number;
  netWeight: number;
  weightUnit: 'kg' | 'lbs' | 'oz' | 'grams';
  itemCount?: number;

  // Quality
  qualityGrade?: 'A' | 'B' | 'C' | 'processing';
  qualityNotes?: string;

  // Storage
  packagingType: string;
  temperatureRequired: TemperatureRange;
  shelfLifeHours: number;

  // For seed saving
  seedsSaved: boolean;
  seedBatchIdCreated?: string;
}

// Processing Event
export interface ProcessingEvent extends BaseTransportEvent {
  eventType: 'processing';

  harvestBatchIds: string[];
  processingBatchId: string;

  processingType: 'washing' | 'cutting' | 'packaging' | 'freezing' | 'drying' | 'canning' | 'juicing' | 'fermenting';

  inputWeight: number;
  outputWeight: number;
  weightUnit: 'kg' | 'lbs';

  wasteWeight: number;
  wasteDisposal: 'compost' | 'animal_feed' | 'biogas' | 'landfill';

  outputProducts: ProcessedProduct[];
}

export interface ProcessedProduct {
  productId: string;
  productType: string;
  quantity: number;
  unit: string;
  shelfLifeDays: number;
  storageRequirements: string;
}

// Distribution Event
export interface DistributionEvent extends BaseTransportEvent {
  eventType: 'distribution';

  batchIds: string[]; // harvest or processing batch IDs
  destinationType: 'consumer' | 'market' | 'restaurant' | 'processor' | 'distributor' | 'vertical_farm';

  // Order info
  orderId?: string;
  customerType: 'individual' | 'business' | 'cooperative' | 'institution';

  // Delivery
  deliveryWindow: {
    start: string;
    end: string;
  };
  actualDeliveryTime?: string;
  deliveryAttempts: number;

  // Chain of custody
  handoffVerified: boolean;
  recipientName?: string;
  recipientSignature?: string;
}

// Consumer Delivery Event
export interface ConsumerDeliveryEvent extends BaseTransportEvent {
  eventType: 'consumer_delivery';

  orderId: string;
  batchIds: string[];

  deliveryMethod: 'home_delivery' | 'pickup_point' | 'farmers_market' | 'csa_distribution' | 'restaurant_delivery';

  // Final mile details
  finalMileMethod: TransportMethod;
  packagingReturned: boolean;
  feedbackReceived: boolean;
  feedbackRating?: number;
  feedbackNotes?: string;
}

// Seed Saving Event
export interface SeedSavingEvent extends BaseTransportEvent {
  eventType: 'seed_saving';

  parentPlantIds: string[];
  newSeedBatchId: string;

  // Seed collection
  collectionMethod: 'dry_seed' | 'wet_seed' | 'fermentation' | 'threshing';
  seedCount?: number;
  seedWeight?: number;
  seedWeightUnit?: 'grams' | 'ounces';

  // Quality testing
  viabilityTestDate?: string;
  germinationRate?: number;
  purityTest?: boolean;
  purityPercentage?: number;

  // Storage
  storageConditions: SeedStorageConditions;
  storageLocationId: string;

  // Lineage
  newGenerationNumber: number;
  geneticNotes?: string;

  // Sharing plans
  availableForSharing: boolean;
  sharingTerms?: 'free' | 'trade' | 'sale' | 'restricted';
}

// Seed Sharing Event
export interface SeedSharingEvent extends BaseTransportEvent {
  eventType: 'seed_sharing';

  seedBatchId: string;
  quantityShared: number;
  quantityUnit: 'seeds' | 'grams' | 'packets';

  sharingType: 'gift' | 'trade' | 'sale' | 'seed_library';
  tradeDetails?: string;
  saleAmount?: number;
  saleCurrency?: string;

  recipientAgreement: boolean;
  growingCommitment?: string;
  reportBackRequired: boolean;
}

// Union type for all transport events
export type TransportEvent =
  | SeedAcquisitionEvent
  | PlantingEvent
  | GrowingTransportEvent
  | HarvestEvent
  | ProcessingEvent
  | DistributionEvent
  | ConsumerDeliveryEvent
  | SeedSavingEvent
  | SeedSharingEvent;

// Transport Block for blockchain
export interface TransportBlock {
  index: number;
  timestamp: string;
  transportEvent: TransportEvent;
  previousHash: string;
  hash: string;
  nonce: number;

  // Cumulative metrics
  cumulativeCarbonKg: number;
  cumulativeFoodMiles: number;
  chainLength: number;
}

// Plant Journey - complete transport history
export interface PlantJourney {
  plantId: string;
  seedBatchOrigin: string;
  currentCustodian: string;
  currentLocation: TransportLocation;
  currentStage: PlantStage;

  events: TransportEvent[];

  // Metrics
  totalFoodMiles: number;
  totalCarbonKg: number;
  daysInTransit: number;
  daysGrowing: number;

  // Lineage
  generation: number;
  ancestorPlantIds: string[];
  descendantSeedBatches: string[];
}

// Environmental Impact Summary
export interface EnvironmentalImpact {
  totalCarbonKg: number;
  totalFoodMiles: number;
  carbonPerKgProduce: number;
  milesPerKgProduce: number;

  breakdownByMethod: Record<TransportMethod, { distance: number; carbon: number }>;
  breakdownByEventType: Record<TransportEventType, { count: number; carbon: number }>;

  comparisonToConventional: {
    carbonSaved: number;
    milesSaved: number;
    percentageReduction: number;
  };
}

// QR Code Data
export interface TransportQRData {
  plantId?: string;
  batchId?: string;
  blockchainAddress: string;
  quickLookupUrl: string;
  lineageHash: string;
  currentCustodian: string;
  lastEventType: TransportEventType;
  lastEventTimestamp: string;
  verificationCode: string;
}
