/**
 * Inventory API Types
 *
 * These types mirror the backend Pydantic schemas exactly.
 * Backend schemas location: services/inventory/app/schemas/
 *
 * @see services/inventory/app/schemas/inventory.py - Base inventory schemas
 * @see services/inventory/app/schemas/food_safety.py - Food safety schemas
 * @see services/inventory/app/schemas/dashboard.py - Dashboard and analytics schemas
 */

// ===== ENUMS =====
// Mirror: app/models/inventory.py

export enum ProductType {
  INGREDIENT = 'INGREDIENT',
  FINISHED_PRODUCT = 'FINISHED_PRODUCT'
}

export enum ProductionStage {
  RAW_INGREDIENT = 'raw_ingredient',
  PAR_BAKED = 'par_baked',
  FULLY_BAKED = 'fully_baked',
  PREPARED_DOUGH = 'prepared_dough',
  FROZEN_PRODUCT = 'frozen_product'
}

export enum UnitOfMeasure {
  KILOGRAMS = 'KILOGRAMS',
  GRAMS = 'GRAMS',
  LITERS = 'LITERS',
  MILLILITERS = 'MILLILITERS',
  UNITS = 'UNITS',
  PIECES = 'PIECES',
  PACKAGES = 'PACKAGES',
  BAGS = 'BAGS',
  BOXES = 'BOXES'
}

export enum IngredientCategory {
  FLOUR = 'flour',
  YEAST = 'yeast',
  DAIRY = 'dairy',
  EGGS = 'eggs',
  SUGAR = 'sugar',
  FATS = 'fats',
  SALT = 'salt',
  SPICES = 'spices',
  ADDITIVES = 'additives',
  PACKAGING = 'packaging',
  CLEANING = 'cleaning',
  OTHER = 'other'
}

export enum ProductCategory {
  BREAD = 'bread',
  CROISSANTS = 'croissants',
  PASTRIES = 'pastries',
  CAKES = 'cakes',
  COOKIES = 'cookies',
  MUFFINS = 'muffins',
  SANDWICHES = 'sandwiches',
  SEASONAL = 'seasonal',
  BEVERAGES = 'beverages',
  OTHER_PRODUCTS = 'other_products'
}

export enum StockMovementType {
  PURCHASE = 'PURCHASE',
  PRODUCTION_USE = 'PRODUCTION_USE',
  ADJUSTMENT = 'ADJUSTMENT',
  WASTE = 'WASTE',
  TRANSFER = 'TRANSFER',
  RETURN = 'RETURN',
  INITIAL_STOCK = 'INITIAL_STOCK',
  TRANSFORMATION = 'TRANSFORMATION'
}

// ===== INGREDIENT SCHEMAS =====
// Mirror: IngredientCreate from inventory.py:34

export interface IngredientCreate {
  name: string;
  product_type?: ProductType;  // Default: INGREDIENT
  sku?: string | null;
  barcode?: string | null;
  category?: string | null;  // Can be ingredient or finished product category
  subcategory?: string | null;
  description?: string | null;
  brand?: string | null;
  unit_of_measure: UnitOfMeasure | string;
  package_size?: number | null;

  // Pricing
  // Note: average_cost is calculated automatically from purchases (not accepted on create)
  standard_cost?: number | null;

  // Stock management - all optional for onboarding
  // These can be configured later based on actual usage patterns
  low_stock_threshold?: number | null;
  reorder_point?: number | null;
  reorder_quantity?: number | null;
  max_stock_level?: number | null;

  // Shelf life (default value only - actual per batch)
  shelf_life_days?: number | null;

  // Properties
  is_perishable?: boolean;  // Default: false
  allergen_info?: Record<string, any> | null;
}

// Mirror: IngredientUpdate from inventory.py:71
export interface IngredientUpdate {
  name?: string | null;
  product_type?: ProductType | null;
  sku?: string | null;
  barcode?: string | null;
  category?: string | null;
  subcategory?: string | null;
  description?: string | null;
  brand?: string | null;
  unit_of_measure?: UnitOfMeasure | string | null;
  package_size?: number | null;

  // Pricing
  average_cost?: number | null;
  standard_cost?: number | null;

  // Stock management
  low_stock_threshold?: number | null;
  reorder_point?: number | null;
  reorder_quantity?: number | null;
  max_stock_level?: number | null;

  // Shelf life (default value only - actual per batch)
  shelf_life_days?: number | null;

  // Properties
  is_active?: boolean | null;
  is_perishable?: boolean | null;
  allergen_info?: Record<string, any> | null;
}

// Mirror: IngredientResponse from inventory.py:103
export interface IngredientResponse {
  id: string;
  tenant_id: string;
  name: string;
  product_type: ProductType;
  sku: string | null;
  barcode: string | null;
  category: string | null;  // Populated from ingredient_category or product_category
  subcategory: string | null;
  description: string | null;
  brand: string | null;
  unit_of_measure: UnitOfMeasure | string;
  package_size: number | null;
  average_cost: number | null;
  last_purchase_price: number | null;
  standard_cost: number | null;
  low_stock_threshold: number | null;  // Now optional
  reorder_point: number | null;  // Now optional
  reorder_quantity: number | null;  // Now optional
  max_stock_level: number | null;
  shelf_life_days: number | null;  // Default value only
  is_active: boolean;
  is_perishable: boolean;
  allergen_info: Record<string, any> | null;
  created_at: string;
  updated_at: string;
  created_by: string | null;

  // Computed fields
  current_stock?: number | null;
  is_low_stock?: boolean | null;
  needs_reorder?: boolean | null;
}

// ===== BULK INGREDIENT SCHEMAS =====
// Mirror: BulkIngredientCreate, BulkIngredientResult, BulkIngredientResponse from inventory.py

export interface BulkIngredientCreate {
  ingredients: IngredientCreate[];
}

export interface BulkIngredientResult {
  index: number;
  success: boolean;
  ingredient: IngredientResponse | null;
  error: string | null;
}

export interface BulkIngredientResponse {
  total_requested: number;
  total_created: number;
  total_failed: number;
  results: BulkIngredientResult[];
  transaction_id: string;
}

// ===== STOCK SCHEMAS =====
// Mirror: StockCreate from inventory.py:140

export interface StockCreate {
  ingredient_id: string;
  supplier_id?: string | null;
  batch_number?: string | null;
  lot_number?: string | null;
  supplier_batch_ref?: string | null;

  // Production stage tracking
  production_stage?: ProductionStage;  // Default: RAW_INGREDIENT
  transformation_reference?: string | null;

  current_quantity: number;
  received_date?: string | null;
  expiration_date?: string | null;
  best_before_date?: string | null;

  // Stage-specific expiration fields
  original_expiration_date?: string | null;
  transformation_date?: string | null;
  final_expiration_date?: string | null;

  unit_cost?: number | null;
  storage_location?: string | null;
  warehouse_zone?: string | null;
  shelf_position?: string | null;

  quality_status?: string;  // Default: "good"

  // Batch-specific storage requirements
  requires_refrigeration?: boolean;  // Default: false
  requires_freezing?: boolean;  // Default: false
  storage_temperature_min?: number | null;
  storage_temperature_max?: number | null;
  storage_humidity_max?: number | null;
  shelf_life_days?: number | null;
  storage_instructions?: string | null;
}

// Mirror: StockUpdate from inventory.py:185
export interface StockUpdate {
  supplier_id?: string | null;
  batch_number?: string | null;
  lot_number?: string | null;
  supplier_batch_ref?: string | null;

  // Production stage tracking
  production_stage?: ProductionStage | null;
  transformation_reference?: string | null;

  current_quantity?: number | null;
  reserved_quantity?: number | null;
  received_date?: string | null;
  expiration_date?: string | null;
  best_before_date?: string | null;

  // Stage-specific expiration fields
  original_expiration_date?: string | null;
  transformation_date?: string | null;
  final_expiration_date?: string | null;

  unit_cost?: number | null;
  storage_location?: string | null;
  warehouse_zone?: string | null;
  shelf_position?: string | null;

  is_available?: boolean | null;
  quality_status?: string | null;

  // Batch-specific storage requirements
  requires_refrigeration?: boolean | null;
  requires_freezing?: boolean | null;
  storage_temperature_min?: number | null;
  storage_temperature_max?: number | null;
  storage_humidity_max?: number | null;
  shelf_life_days?: number | null;
  storage_instructions?: string | null;
}

// Mirror: StockResponse from inventory.py:225
export interface StockResponse {
  id: string;
  tenant_id: string;
  ingredient_id: string;
  supplier_id: string | null;
  batch_number: string | null;
  lot_number: string | null;
  supplier_batch_ref: string | null;

  // Production stage tracking
  production_stage: ProductionStage;
  transformation_reference: string | null;

  current_quantity: number;
  reserved_quantity: number;
  available_quantity: number;
  received_date: string | null;
  expiration_date: string | null;
  best_before_date: string | null;

  // Stage-specific expiration fields
  original_expiration_date: string | null;
  transformation_date: string | null;
  final_expiration_date: string | null;

  unit_cost: number | null;
  total_cost: number | null;
  storage_location: string | null;
  warehouse_zone: string | null;
  shelf_position: string | null;
  is_available: boolean;
  is_expired: boolean;
  quality_status: string;

  // Batch-specific storage requirements
  requires_refrigeration: boolean;
  requires_freezing: boolean;
  storage_temperature_min: number | null;
  storage_temperature_max: number | null;
  storage_humidity_max: number | null;
  shelf_life_days: number | null;
  storage_instructions: string | null;
  created_at: string;
  updated_at: string;

  // Related data
  ingredient?: IngredientResponse | null;
}

// ===== BULK STOCK SCHEMAS =====
// Mirror: BulkStockCreate, BulkStockResult, BulkStockResponse from inventory.py

export interface BulkStockCreate {
  stocks: StockCreate[];
}

export interface BulkStockResult {
  index: number;
  success: boolean;
  stock: StockResponse | null;
  error: string | null;
}

export interface BulkStockResponse {
  total_requested: number;
  total_created: number;
  total_failed: number;
  results: BulkStockResult[];
  transaction_id: string;
}

// ===== STOCK MOVEMENT SCHEMAS =====
// Mirror: StockMovementCreate from inventory.py:277

export interface StockMovementCreate {
  ingredient_id: string;
  stock_id?: string | null;
  movement_type: StockMovementType;
  quantity: number;
  unit_cost?: number | null;
  reference_number?: string | null;
  supplier_id?: string | null;
  notes?: string | null;
  reason_code?: string | null;
  movement_date?: string | null;
}

// Mirror: StockMovementResponse from inventory.py:293
export interface StockMovementResponse {
  id: string;
  tenant_id: string;
  ingredient_id: string;
  stock_id: string | null;
  movement_type: StockMovementType;
  quantity: number;
  unit_cost: number | null;
  total_cost: number | null;
  quantity_before: number | null;
  quantity_after: number | null;
  reference_number: string | null;
  supplier_id: string | null;
  notes: string | null;
  reason_code: string | null;
  movement_date: string;
  created_at: string;
  created_by: string | null;

  // Related data
  ingredient?: IngredientResponse | null;
}

// ===== PRODUCT TRANSFORMATION SCHEMAS =====
// Mirror: ProductTransformationCreate from inventory.py:319

export interface ProductTransformationCreate {
  source_ingredient_id: string;
  target_ingredient_id: string;
  source_stage: ProductionStage;
  target_stage: ProductionStage;
  source_quantity: number;
  target_quantity: number;
  conversion_ratio?: number | null;
  expiration_calculation_method?: string;  // Default: "days_from_transformation"
  expiration_days_offset?: number | null;  // Default: 1
  process_notes?: string | null;
  target_batch_number?: string | null;
  source_stock_ids?: string[] | null;
}

// Mirror: ProductTransformationResponse from inventory.py:342
export interface ProductTransformationResponse {
  id: string;
  tenant_id: string;
  transformation_reference: string;
  source_ingredient_id: string;
  target_ingredient_id: string;
  source_stage: ProductionStage;
  target_stage: ProductionStage;
  source_quantity: number;
  target_quantity: number;
  conversion_ratio: number;
  expiration_calculation_method: string;
  expiration_days_offset: number | null;
  transformation_date: string;
  process_notes: string | null;
  performed_by: string | null;
  source_batch_numbers: string | null;
  target_batch_number: string | null;
  is_completed: boolean;
  is_reversed: boolean;
  created_at: string;
  created_by: string | null;

  // Related data
  source_ingredient?: IngredientResponse | null;
  target_ingredient?: IngredientResponse | null;
}

// ===== FILTER SCHEMAS =====
// Mirror: InventoryFilter from inventory.py:460

export interface InventoryFilter {
  category?: IngredientCategory | null;
  is_active?: boolean | null;
  is_low_stock?: boolean | null;
  needs_reorder?: boolean | null;
  search?: string | null;
}

// Mirror: StockFilter from inventory.py:469
export interface StockFilter {
  ingredient_id?: string | null;
  production_stage?: ProductionStage | null;
  transformation_reference?: string | null;
  is_available?: boolean | null;
  is_expired?: boolean | null;
  expiring_within_days?: number | null;
  storage_location?: string | null;
  quality_status?: string | null;
}

// ===== OPERATIONS SCHEMAS =====
// From inventory_operations.py

export interface StockConsumptionRequest {
  ingredient_id: string;
  quantity: number;
  reference_number?: string | null;
  notes?: string | null;
  fifo?: boolean;  // Default: true
}

export interface StockConsumptionResponse {
  ingredient_id: string;
  total_quantity_consumed: number;
  consumed_items: Array<{
    stock_id: string;
    quantity_consumed: number;
    batch_number?: string | null;
    expiration_date?: string | null;
  }>;
  method: 'FIFO' | 'LIFO';
}

// Product Classification (from inventory_operations.py:149-195)
export interface ProductClassificationRequest {
  product_name: string;
  sales_volume?: number | null;
  sales_data?: Record<string, any>;
}

export interface BatchClassificationRequest {
  products: ProductClassificationRequest[];
}

export interface ProductSuggestionResponse {
  suggestion_id: string;
  original_name: string;
  suggested_name: string;
  product_type: string;
  category: string;
  unit_of_measure: string;
  confidence_score: number;
  estimated_shelf_life_days: number | null;
  requires_refrigeration: boolean;
  requires_freezing: boolean;
  is_seasonal: boolean;
  suggested_supplier: string | null;
  notes: string | null;
  sales_data?: {
    total_quantity: number;
    average_daily_sales: number;
    peak_day: string;
    frequency: number;
  };
}

export interface BusinessModelAnalysisResponse {
  model: string;
  confidence: number;
  ingredient_count: number;
  finished_product_count: number;
  ingredient_ratio: number;
  recommendations: string[];
}

export interface BatchClassificationResponse {
  suggestions: ProductSuggestionResponse[];
  business_model_analysis: BusinessModelAnalysisResponse;
  total_products: number;
  high_confidence_count: number;
  low_confidence_count: number;
}

// ===== FOOD SAFETY SCHEMAS =====
// Mirror: food_safety.py

export interface TemperatureLogCreate {
  tenant_id: string;
  storage_location: string;
  warehouse_zone?: string | null;
  equipment_id?: string | null;
  temperature_celsius: number;
  humidity_percentage?: number | null;
  target_temperature_min?: number | null;
  target_temperature_max?: number | null;
  measurement_method?: string;  // Default: "manual"
  device_id?: string | null;
  calibration_date?: string | null;
}

export interface TemperatureLogResponse {
  id: string;
  tenant_id: string;
  storage_location: string;
  warehouse_zone: string | null;
  equipment_id: string | null;
  temperature_celsius: number;
  humidity_percentage: number | null;
  target_temperature_min: number | null;
  target_temperature_max: number | null;
  measurement_method: string;
  device_id: string | null;
  calibration_date: string | null;
  is_within_range: boolean;
  alert_triggered: boolean;
  deviation_minutes: number | null;
  recorded_at: string;
  created_at: string;
  recorded_by: string | null;
}

export interface FoodSafetyAlertResponse {
  id: string;
  tenant_id: string;
  alert_code: string;
  alert_type: string;
  severity: string;
  risk_level: string;
  source_entity_type: string;
  source_entity_id: string;
  ingredient_id: string | null;
  stock_id: string | null;
  title: string;
  description: string;
  detailed_message: string | null;
  regulatory_requirement: string | null;
  compliance_standard: string | null;
  regulatory_action_required: boolean;
  trigger_condition: string | null;
  threshold_value: number | null;
  actual_value: number | null;
  alert_data: Record<string, any> | null;
  environmental_factors: Record<string, any> | null;
  affected_products: string[] | null;
  public_health_risk: boolean;
  business_impact: string | null;
  estimated_loss: number | null;
  status: string;
  alert_state: string;
  immediate_actions_taken: string[] | null;
  investigation_notes: string | null;
  resolution_action: string | null;
  resolution_notes: string | null;
  corrective_actions: string[] | null;
  preventive_measures: string[] | null;
  first_occurred_at: string;
  last_occurred_at: string;
  acknowledged_at: string | null;
  resolved_at: string | null;
  escalation_deadline: string | null;
  occurrence_count: number;
  is_recurring: boolean;
  recurrence_pattern: string | null;
  assigned_to: string | null;
  assigned_role: string | null;
  escalated_to: string | null;
  escalation_level: number;
  notification_sent: boolean;
  notification_methods: string[] | null;
  notification_recipients: string[] | null;
  regulatory_notification_required: boolean;
  regulatory_notification_sent: boolean;
  documentation: Record<string, any> | null;
  audit_trail: Array<Record<string, any>> | null;
  external_reference: string | null;
  detection_time: string | null;
  response_time_minutes: number | null;
  resolution_time_minutes: number | null;
  alert_accuracy: boolean | null;
  false_positive: boolean;
  feedback_notes: string | null;
  created_at: string;
  updated_at: string;
  created_by: string | null;
  updated_by: string | null;
}

export interface FoodSafetyComplianceResponse {
  id: string;
  tenant_id: string;
  ingredient_id: string;
  standard: string;
  compliance_status: string;
  certification_number: string | null;
  certifying_body: string | null;
  certification_date: string | null;
  expiration_date: string | null;
  requirements: Record<string, any> | null;
  compliance_notes: string | null;
  documentation_url: string | null;
  last_audit_date: string | null;
  next_audit_date: string | null;
  auditor_name: string | null;
  audit_score: number | null;
  risk_level: string;
  risk_factors: string[] | null;
  mitigation_measures: string[] | null;
  requires_monitoring: boolean;
  monitoring_frequency_days: number | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  created_by: string | null;
  updated_by: string | null;
}

// ===== DASHBOARD SCHEMAS =====
// Mirror: dashboard.py

export interface InventorySummary {
  total_ingredients: number;
  total_stock_value: number;
  low_stock_alerts: number;
  expiring_soon_items: number;
  expired_items: number;
  out_of_stock_items: number;
  stock_by_category: Record<string, Record<string, any>>;
  recent_movements: number;
  recent_purchases: number;
  recent_waste: number;
}

export interface InventoryDashboardSummary {
  total_ingredients: number;
  active_ingredients: number;
  total_stock_value: number;
  total_stock_items: number;
  in_stock_items: number;
  low_stock_items: number;
  out_of_stock_items: number;
  expired_items: number;
  expiring_soon_items: number;
  food_safety_alerts_active: number;
  temperature_violations_today: number;
  compliance_issues: number;
  certifications_expiring_soon: number;
  recent_stock_movements: number;
  recent_purchases: number;
  recent_waste: number;
  recent_adjustments: number;
  business_model: string | null;
  business_model_confidence: number | null;
  stock_by_category: Record<string, any>;
  alerts_by_severity: Record<string, number>;
  movements_by_type: Record<string, number>;
  inventory_turnover_ratio: number | null;
  waste_percentage: number | null;
  compliance_score: number | null;
  cost_per_unit_avg: number | null;
  stock_value_trend: Array<Record<string, any>>;
  alert_trend: Array<Record<string, any>>;
}

export interface InventoryAnalytics {
  inventory_turnover_rate: number;
  fast_moving_items: Array<Record<string, any>>;
  slow_moving_items: Array<Record<string, any>>;
  dead_stock_items: Array<Record<string, any>>;
  total_inventory_cost: number;
  cost_by_category: Record<string, number>;
  average_unit_cost_trend: Array<Record<string, any>>;
  waste_cost_analysis: Record<string, any>;
  stockout_frequency: Record<string, number>;
  overstock_frequency: Record<string, number>;
  reorder_accuracy: number;
  forecast_accuracy: number;
  quality_incidents_rate: number;
  food_safety_score: number;
  compliance_score_by_standard: Record<string, number>;
  temperature_compliance_rate: number;
  supplier_performance: Array<Record<string, any>>;
  delivery_reliability: number;
  quality_consistency: number;
}

// ===== PAGINATION =====
// Mirror: PaginatedResponse from inventory.py:448

export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  size: number;
  pages: number;
}

// ===== DELETION SUMMARY =====
export interface DeletionSummary {
  ingredient_id: string;
  ingredient_name: string | null;
  deleted_stock_entries: number;
  deleted_stock_movements: number;
  deleted_stock_alerts: number;
  success: boolean;
}
