/**
 * TypeScript types for Orders Service
 * Based on backend schemas in services/orders/app/schemas/order_schemas.py
 */

export enum CustomerType {
  INDIVIDUAL = 'individual',
  BUSINESS = 'business',
  CENTRAL_BAKERY = 'central_bakery'
}

export enum DeliveryMethod {
  DELIVERY = 'delivery',
  PICKUP = 'pickup'
}

export enum PaymentTerms {
  IMMEDIATE = 'immediate',
  NET_30 = 'net_30',
  NET_60 = 'net_60'
}

export enum PaymentMethod {
  CASH = 'cash',
  CARD = 'card',
  BANK_TRANSFER = 'bank_transfer',
  ACCOUNT = 'account'
}

export enum PaymentStatus {
  PENDING = 'pending',
  PARTIAL = 'partial',
  PAID = 'paid',
  FAILED = 'failed',
  REFUNDED = 'refunded'
}

export enum CustomerSegment {
  VIP = 'vip',
  REGULAR = 'regular',
  WHOLESALE = 'wholesale'
}

export enum PriorityLevel {
  HIGH = 'high',
  NORMAL = 'normal',
  LOW = 'low'
}

export enum OrderType {
  STANDARD = 'standard',
  RUSH = 'rush',
  RECURRING = 'recurring',
  SPECIAL = 'special'
}

export enum OrderStatus {
  PENDING = 'pending',
  CONFIRMED = 'confirmed',
  IN_PRODUCTION = 'in_production',
  READY = 'ready',
  OUT_FOR_DELIVERY = 'out_for_delivery',
  DELIVERED = 'delivered',
  CANCELLED = 'cancelled',
  FAILED = 'failed'
}

export enum OrderSource {
  MANUAL = 'manual',
  ONLINE = 'online',
  PHONE = 'phone',
  APP = 'app',
  API = 'api'
}

export enum SalesChannel {
  DIRECT = 'direct',
  WHOLESALE = 'wholesale',
  RETAIL = 'retail'
}

export enum BusinessModel {
  INDIVIDUAL_BAKERY = 'individual_bakery',
  CENTRAL_BAKERY = 'central_bakery'
}

// ===== Customer Types =====

export interface CustomerBase {
  name: string;
  business_name?: string;
  customer_type: CustomerType;
  email?: string;
  phone?: string;
  address_line1?: string;
  address_line2?: string;
  city?: string;
  state?: string;
  postal_code?: string;
  country: string;
  is_active: boolean;
  preferred_delivery_method: DeliveryMethod;
  payment_terms: PaymentTerms;
  credit_limit?: number;
  discount_percentage: number;
  customer_segment: CustomerSegment;
  priority_level: PriorityLevel;
  special_instructions?: string;
  delivery_preferences?: Record<string, any>;
  product_preferences?: Record<string, any>;
}

export interface CustomerCreate extends CustomerBase {
  customer_code: string;
  tenant_id: string;
}

export interface CustomerUpdate extends Partial<Omit<CustomerBase, 'country' | 'is_active' | 'preferred_delivery_method' | 'payment_terms' | 'discount_percentage' | 'customer_segment' | 'priority_level'>> {
  country?: string;
  is_active?: boolean;
  preferred_delivery_method?: DeliveryMethod;
  payment_terms?: PaymentTerms;
  discount_percentage?: number;
  customer_segment?: CustomerSegment;
  priority_level?: PriorityLevel;
}

export interface CustomerResponse extends CustomerBase {
  id: string;
  tenant_id: string;
  customer_code: string;
  total_orders: number;
  total_spent: number;
  average_order_value: number;
  last_order_date?: string;
  created_at: string;
  updated_at: string;
}

// ===== Order Item Types =====

export interface OrderItemBase {
  product_id: string;
  product_name: string;
  product_sku?: string;
  product_category?: string;
  quantity: number;
  unit_of_measure: string;
  weight?: number;
  unit_price: number;
  line_discount: number;
  product_specifications?: Record<string, any>;
  customization_details?: string;
  special_instructions?: string;
  recipe_id?: string;
}

export interface OrderItemCreate extends OrderItemBase {}

export interface OrderItemUpdate {
  quantity?: number;
  unit_price?: number;
  line_discount?: number;
  product_specifications?: Record<string, any>;
  customization_details?: string;
  special_instructions?: string;
}

export interface OrderItemResponse extends OrderItemBase {
  id: string;
  order_id: string;
  line_total: number;
  status: string;
  created_at: string;
  updated_at: string;
}

// ===== Order Types =====

export interface OrderBase {
  customer_id: string;
  order_type: OrderType;
  priority: PriorityLevel;
  requested_delivery_date: string;
  delivery_method: DeliveryMethod;
  delivery_address?: Record<string, any>;
  delivery_instructions?: string;
  delivery_window_start?: string;
  delivery_window_end?: string;
  discount_percentage: number;
  delivery_fee: number;
  payment_method?: PaymentMethod;
  payment_terms: PaymentTerms;
  special_instructions?: string;
  custom_requirements?: Record<string, any>;
  allergen_warnings?: Record<string, any>;
  order_source: OrderSource;
  sales_channel: SalesChannel;
  order_origin?: string;
  communication_preferences?: Record<string, any>;
}

export interface OrderCreate extends OrderBase {
  tenant_id: string;
  items: OrderItemCreate[];
}

export interface OrderUpdate {
  status?: OrderStatus;
  priority?: PriorityLevel;
  requested_delivery_date?: string;
  confirmed_delivery_date?: string;
  delivery_method?: DeliveryMethod;
  delivery_address?: Record<string, any>;
  delivery_instructions?: string;
  delivery_window_start?: string;
  delivery_window_end?: string;
  payment_method?: PaymentMethod;
  payment_status?: PaymentStatus;
  special_instructions?: string;
  custom_requirements?: Record<string, any>;
  allergen_warnings?: Record<string, any>;
}

export interface OrderResponse extends OrderBase {
  id: string;
  tenant_id: string;
  order_number: string;
  status: OrderStatus;
  order_date: string;
  confirmed_delivery_date?: string;
  actual_delivery_date?: string;
  subtotal: number;
  discount_amount: number;
  tax_amount: number;
  total_amount: number;
  payment_status: PaymentStatus;
  business_model?: string;
  estimated_business_model?: string;
  production_batch_id?: string;
  quality_score?: number;
  customer_rating?: number;
  created_at: string;
  updated_at: string;
  items: OrderItemResponse[];
}

// ===== Dashboard and Analytics Types =====

export interface OrdersDashboardSummary {
  // Current period metrics
  total_orders_today: number;
  total_orders_this_week: number;
  total_orders_this_month: number;
  
  // Revenue metrics
  revenue_today: number;
  revenue_this_week: number;
  revenue_this_month: number;
  
  // Order status breakdown
  pending_orders: number;
  confirmed_orders: number;
  in_production_orders: number;
  ready_orders: number;
  delivered_orders: number;
  
  // Customer metrics
  total_customers: number;
  new_customers_this_month: number;
  repeat_customers_rate: number;
  
  // Performance metrics
  average_order_value: number;
  order_fulfillment_rate: number;
  on_time_delivery_rate: number;
  
  // Business model detection
  business_model?: string;
  business_model_confidence?: number;
  
  // Recent activity
  recent_orders: OrderResponse[];
  high_priority_orders: OrderResponse[];
}

export interface DemandRequirements {
  date: string;
  tenant_id: string;
  
  // Product demand breakdown
  product_demands: Record<string, any>[];
  
  // Aggregate metrics
  total_orders: number;
  total_quantity: number;
  total_value: number;
  
  // Business context
  business_model?: string;
  rush_orders_count: number;
  special_requirements: string[];
  
  // Timing requirements
  earliest_delivery: string;
  latest_delivery: string;
  average_lead_time_hours: number;
}

export interface BusinessModelDetection {
  business_model: string;
  confidence: string;
  detected_at: string;
}

export interface ServiceStatus {
  service: string;
  status: string;
  timestamp: string;
  tenant_id: string;
}

// ===== Query Parameters Types =====

export interface GetOrdersParams {
  tenant_id: string;
  status_filter?: string;
  start_date?: string;
  end_date?: string;
  skip?: number;
  limit?: number;
}

export interface GetCustomersParams {
  tenant_id: string;
  active_only?: boolean;
  skip?: number;
  limit?: number;
}

export interface UpdateOrderStatusParams {
  tenant_id: string;
  order_id: string;
  new_status: OrderStatus;
  reason?: string;
}

export interface GetDemandRequirementsParams {
  tenant_id: string;
  target_date: string;
}

// ===== Procurement Types =====

export type ProcurementPlanType = 'regular' | 'emergency' | 'seasonal';
export type ProcurementStrategy = 'just_in_time' | 'bulk' | 'mixed';
export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
export type RequirementStatus = 'pending' | 'approved' | 'ordered' | 'partially_received' | 'received' | 'cancelled';
export type PlanStatus = 'draft' | 'pending_approval' | 'approved' | 'in_execution' | 'completed' | 'cancelled';
export type DeliveryStatus = 'pending' | 'in_transit' | 'delivered' | 'delayed' | 'cancelled';

// Procurement Requirement Types
export interface ProcurementRequirementBase {
  product_id: string;
  product_name: string;
  product_sku?: string;
  product_category?: string;
  product_type: string;
  required_quantity: number;
  unit_of_measure: string;
  safety_stock_quantity: number;
  total_quantity_needed: number;
  current_stock_level: number;
  reserved_stock: number;
  available_stock: number;
  net_requirement: number;
  order_demand: number;
  production_demand: number;
  forecast_demand: number;
  buffer_demand: number;
  required_by_date: string;
  lead_time_buffer_days: number;
  suggested_order_date: string;
  latest_order_date: string;
  priority: PriorityLevel;
  risk_level: RiskLevel;
  preferred_supplier_id?: string;
  backup_supplier_id?: string;
  supplier_name?: string;
  supplier_lead_time_days?: number;
  minimum_order_quantity?: number;
  estimated_unit_cost?: number;
  estimated_total_cost?: number;
  last_purchase_cost?: number;
}

export interface ProcurementRequirementCreate extends ProcurementRequirementBase {
  special_requirements?: string;
  storage_requirements?: string;
  shelf_life_days?: number;
  quality_specifications?: Record<string, any>;
  procurement_notes?: string;
}

export interface ProcurementRequirementUpdate {
  status?: RequirementStatus;
  priority?: PriorityLevel;
  approved_quantity?: number;
  approved_cost?: number;
  purchase_order_id?: string;
  purchase_order_number?: string;
  ordered_quantity?: number;
  expected_delivery_date?: string;
  actual_delivery_date?: string;
  received_quantity?: number;
  delivery_status?: DeliveryStatus;
  procurement_notes?: string;
}

export interface ProcurementRequirementResponse extends ProcurementRequirementBase {
  id: string;
  plan_id: string;
  requirement_number: string;
  status: RequirementStatus;
  created_at: string;
  updated_at: string;
  purchase_order_id?: string;
  purchase_order_number?: string;
  ordered_quantity: number;
  ordered_at?: string;
  expected_delivery_date?: string;
  actual_delivery_date?: string;
  received_quantity: number;
  delivery_status: DeliveryStatus;
  fulfillment_rate?: number;
  on_time_delivery?: boolean;
  quality_rating?: number;
  approved_quantity?: number;
  approved_cost?: number;
  approved_at?: string;
  approved_by?: string;
  special_requirements?: string;
  storage_requirements?: string;
  shelf_life_days?: number;
  quality_specifications?: Record<string, any>;
  procurement_notes?: string;
}

// Procurement Plan Types
export interface ProcurementPlanBase {
  plan_date: string;
  plan_period_start: string;
  plan_period_end: string;
  planning_horizon_days: number;
  plan_type: ProcurementPlanType;
  priority: PriorityLevel;
  business_model?: BusinessModel;
  procurement_strategy: ProcurementStrategy;
  safety_stock_buffer: number;
  supply_risk_level: RiskLevel;
  demand_forecast_confidence?: number;
  seasonality_adjustment: number;
  special_requirements?: string;
}

export interface ProcurementPlanCreate extends ProcurementPlanBase {
  tenant_id: string;
  requirements?: ProcurementRequirementCreate[];
}

export interface ProcurementPlanUpdate {
  status?: PlanStatus;
  priority?: PriorityLevel;
  approved_at?: string;
  approved_by?: string;
  execution_started_at?: string;
  execution_completed_at?: string;
  special_requirements?: string;
  seasonal_adjustments?: Record<string, any>;
}

export interface ProcurementPlanResponse extends ProcurementPlanBase {
  id: string;
  tenant_id: string;
  plan_number: string;
  status: PlanStatus;
  total_requirements: number;
  total_estimated_cost: number;
  total_approved_cost: number;
  cost_variance: number;
  total_demand_orders: number;
  total_demand_quantity: number;
  total_production_requirements: number;
  primary_suppliers_count: number;
  backup_suppliers_count: number;
  supplier_diversification_score?: number;
  approved_at?: string;
  approved_by?: string;
  execution_started_at?: string;
  execution_completed_at?: string;
  fulfillment_rate?: number;
  on_time_delivery_rate?: number;
  cost_accuracy?: number;
  quality_score?: number;
  created_at: string;
  updated_at: string;
  created_by?: string;
  updated_by?: string;
  requirements: ProcurementRequirementResponse[];
}

// Summary and Dashboard Types
export interface ProcurementSummary {
  total_plans: number;
  active_plans: number;
  total_requirements: number;
  pending_requirements: number;
  critical_requirements: number;
  total_estimated_cost: number;
  total_approved_cost: number;
  cost_variance: number;
  average_fulfillment_rate?: number;
  average_on_time_delivery?: number;
  top_suppliers: Record<string, any>[];
  critical_items: Record<string, any>[];
}

export interface ProcurementDashboardData {
  current_plan?: ProcurementPlanResponse;
  summary: ProcurementSummary;
  upcoming_deliveries: Record<string, any>[];
  overdue_requirements: Record<string, any>[];
  low_stock_alerts: Record<string, any>[];
  performance_metrics: Record<string, any>;
}

// Request and Response Types
export interface GeneratePlanRequest {
  plan_date?: string;
  force_regenerate: boolean;
  planning_horizon_days: number;
  include_safety_stock: boolean;
  safety_stock_percentage: number;
}

export interface GeneratePlanResponse {
  success: boolean;
  message: string;
  plan?: ProcurementPlanResponse;
  warnings: string[];
  errors: string[];
}

export interface PaginatedProcurementPlans {
  plans: ProcurementPlanResponse[];
  total: number;
  page: number;
  limit: number;
  has_more: boolean;
}

export interface ForecastRequest {
  target_date: string;
  horizon_days: number;
  include_confidence_intervals: boolean;
  product_ids?: string[];
}

// Query Parameter Types for Procurement
export interface GetProcurementPlansParams {
  tenant_id: string;
  status?: string;
  start_date?: string;
  end_date?: string;
  limit?: number;
  offset?: number;
}

export interface GetPlanRequirementsParams {
  tenant_id: string;
  plan_id: string;
  status?: string;
  priority?: string;
}

export interface UpdatePlanStatusParams {
  tenant_id: string;
  plan_id: string;
  status: PlanStatus;
}