/**
 * TypeScript types for Procurement Service
 * Mirrored from backend schemas: services/procurement/app/schemas/procurement_schemas.py
 * Backend enums: services/shared/app/models/enums.py
 * Backend API: services/procurement/app/api/
 *
 * Coverage:
 * - Procurement Plans (MRP-style procurement planning)
 * - Procurement Requirements (demand-driven purchasing)
 * - Purchase Orders creation from plans
 * - Analytics & Dashboard
 * - Auto-generation (Orchestrator integration)
 */

// ================================================================
// ENUMS
// ================================================================

/**
 * Procurement plan types
 * Backend: ProcurementPlanType enum in models/enums.py
 */
export enum ProcurementPlanType {
  REGULAR = 'regular',
  EMERGENCY = 'emergency',
  SEASONAL = 'seasonal'
}

/**
 * Procurement strategies
 * Backend: ProcurementStrategy enum in models/enums.py
 */
export enum ProcurementStrategy {
  JUST_IN_TIME = 'just_in_time',
  BULK = 'bulk',
  MIXED = 'mixed'
}

/**
 * Risk level classifications
 * Backend: RiskLevel enum in models/enums.py
 */
export enum RiskLevel {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  CRITICAL = 'critical'
}

/**
 * Procurement requirement status
 * Backend: RequirementStatus enum in models/enums.py
 */
export enum RequirementStatus {
  PENDING = 'pending',
  APPROVED = 'approved',
  ORDERED = 'ordered',
  PARTIALLY_RECEIVED = 'partially_received',
  RECEIVED = 'received',
  CANCELLED = 'cancelled'
}

/**
 * Procurement plan status
 * Backend: PlanStatus enum in models/enums.py
 */
export enum PlanStatus {
  DRAFT = 'draft',
  PENDING_APPROVAL = 'pending_approval',
  APPROVED = 'approved',
  IN_EXECUTION = 'in_execution',
  COMPLETED = 'completed',
  CANCELLED = 'cancelled'
}

/**
 * Delivery status for procurement
 * Backend: DeliveryStatus enum in models/enums.py
 */
export enum DeliveryStatus {
  PENDING = 'pending',
  IN_TRANSIT = 'in_transit',
  DELIVERED = 'delivered',
  DELAYED = 'delayed',
  CANCELLED = 'cancelled'
}

/**
 * Priority level (shared enum)
 * Backend: PriorityLevel enum in models/enums.py
 */
export enum PriorityLevel {
  HIGH = 'high',
  NORMAL = 'normal',
  LOW = 'low'
}

/**
 * Business model (shared enum)
 * Backend: BusinessModel enum in models/enums.py
 */
export enum BusinessModel {
  INDIVIDUAL_BAKERY = 'individual_bakery',
  CENTRAL_BAKERY = 'central_bakery'
}

// ================================================================
// PROCUREMENT REQUIREMENT TYPES
// ================================================================

/**
 * Base procurement requirement
 * Backend: ProcurementRequirementBase schema
 */
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;
}

/**
 * Create procurement requirement request
 * Backend: ProcurementRequirementCreate schema
 */
export interface ProcurementRequirementCreate extends ProcurementRequirementBase {
  special_requirements?: string;
  storage_requirements?: string;
  shelf_life_days?: number;
  quality_specifications?: Record<string, any>;
  procurement_notes?: string;

  // Smart procurement calculation metadata
  calculation_method?: string;
  ai_suggested_quantity?: number;
  adjusted_quantity?: number;
  adjustment_reason?: string;
  price_tier_applied?: Record<string, any>;
  supplier_minimum_applied?: boolean;
  storage_limit_applied?: boolean;
  reorder_rule_applied?: boolean;

  // Local production support fields
  is_locally_produced?: boolean;
  recipe_id?: string;
  parent_requirement_id?: string;
  bom_explosion_level?: number;
}

/**
 * Update procurement requirement request
 * Backend: ProcurementRequirementUpdate schema
 */
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;
}

/**
 * Procurement requirement response
 * Backend: ProcurementRequirementResponse schema
 */
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;

  // Smart procurement calculation metadata
  calculation_method?: string;
  ai_suggested_quantity?: number;
  adjusted_quantity?: number;
  adjustment_reason?: string;
  price_tier_applied?: Record<string, any>;
  supplier_minimum_applied?: boolean;
  storage_limit_applied?: boolean;
  reorder_rule_applied?: boolean;

  // Local production support fields
  is_locally_produced?: boolean;
  recipe_id?: string;
  parent_requirement_id?: string;
  bom_explosion_level?: number;
}

// ================================================================
// PROCUREMENT PLAN TYPES
// ================================================================

/**
 * Base procurement plan
 * Backend: ProcurementPlanBase schema
 */
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;
}

/**
 * Create procurement plan request
 * Backend: ProcurementPlanCreate schema
 */
export interface ProcurementPlanCreate extends ProcurementPlanBase {
  tenant_id: string;
  requirements?: ProcurementRequirementCreate[];
}

/**
 * Update procurement plan request
 * Backend: ProcurementPlanUpdate schema
 */
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>;
}

/**
 * Approval workflow entry
 * Backend: ApprovalWorkflowEntry (embedded in plan)
 */
export interface ApprovalWorkflowEntry {
  timestamp: string;
  from_status: string;
  to_status: string;
  user_id?: string;
  notes?: string;
}

/**
 * Procurement plan response
 * Backend: ProcurementPlanResponse schema
 */
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;
  approval_workflow?: ApprovalWorkflowEntry[];
  created_at: string;
  updated_at: string;
  created_by?: string;
  updated_by?: string;
  requirements: ProcurementRequirementResponse[];
}

// ================================================================
// ANALYTICS & DASHBOARD TYPES
// ================================================================

/**
 * Procurement summary metrics
 * Backend: Returned by analytics endpoints
 */
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>[];
}

/**
 * Procurement dashboard data
 * Backend: GET /api/v1/tenants/{tenant_id}/procurement/analytics/procurement
 */
export interface ProcurementDashboardData {
  current_plan?: ProcurementPlanResponse;
  summary: {
    total_plans: number;
    total_estimated_cost: number;
    total_approved_cost: number;
    cost_variance: number;
  };
  upcoming_deliveries?: Record<string, any>[];
  overdue_requirements?: Record<string, any>[];
  low_stock_alerts?: Record<string, any>[];
  performance_metrics: {
    average_fulfillment_rate: number;
    average_on_time_delivery: number;
    cost_accuracy: number;
    supplier_performance: number;
    fulfillment_trend?: number;
    on_time_trend?: number;
    cost_variance_trend?: number;
  };

  plan_status_distribution?: Array<{
    status: string;
    count: number;
  }>;
  critical_requirements?: {
    low_stock: number;
    overdue: number;
    high_priority: number;
  };
  recent_plans?: Array<{
    id: string;
    plan_number: string;
    plan_date: string;
    status: string;
    total_requirements: number;
    total_estimated_cost: number;
    created_at: string;
  }>;
  supplier_performance?: Array<{
    id: string;
    name: string;
    total_orders: number;
    fulfillment_rate: number;
    on_time_rate: number;
    quality_score: number;
  }>;
  cost_by_category?: Array<{
    name: string;
    amount: number;
  }>;
  quality_metrics?: {
    avg_score: number;
    high_quality_count: number;
    low_quality_count: number;
  };
}

/**
 * Procurement trends data for time-series charts
 * Backend: GET /api/v1/tenants/{tenant_id}/procurement/analytics/procurement/trends
 */
export interface ProcurementTrendsData {
  performance_trend: Array<{
    date: string;
    fulfillment_rate: number;
    on_time_rate: number;
  }>;
  quality_trend: Array<{
    date: string;
    quality_score: number;
  }>;
  period_days: number;
  start_date: string;
  end_date: string;
}

// ================================================================
// REQUEST & RESPONSE TYPES
// ================================================================

/**
 * Generate procurement plan request
 * Backend: POST /api/v1/tenants/{tenant_id}/procurement/plans/generate
 */
export interface GeneratePlanRequest {
  plan_date?: string;
  force_regenerate: boolean;
  planning_horizon_days: number;
  include_safety_stock: boolean;
  safety_stock_percentage: number;
}

/**
 * Generate procurement plan response
 * Backend: POST /api/v1/tenants/{tenant_id}/procurement/plans/generate
 */
export interface GeneratePlanResponse {
  success: boolean;
  message: string;
  plan?: ProcurementPlanResponse;
  warnings: string[];
  errors: string[];
}

/**
 * Auto-generate procurement request (Orchestrator integration)
 * Backend: POST /api/v1/tenants/{tenant_id}/procurement/auto-generate
 */
export interface AutoGenerateProcurementRequest {
  forecast_data: Record<string, any>;
  production_schedule_id?: string;
  target_date?: string;
  planning_horizon_days: number;
  safety_stock_percentage: number;
  auto_create_pos: boolean;
  auto_approve_pos: boolean;

  // Cached data from Orchestrator
  inventory_data?: Record<string, any>;
  suppliers_data?: Record<string, any>;
  recipes_data?: Record<string, any>;
}

/**
 * Auto-generate procurement response
 * Backend: POST /api/v1/tenants/{tenant_id}/procurement/auto-generate
 */
export interface AutoGenerateProcurementResponse {
  success: boolean;
  message: string;
  plan_id?: string;
  plan_number?: string;
  requirements_created: number;
  purchase_orders_created: number;
  purchase_orders_auto_approved: number;
  total_estimated_cost: number;
  warnings: string[];
  errors: string[];
  created_pos: Array<{
    po_id: string;
    po_number: string;
    supplier_id: string;
    items_count: number;
    total_amount: number;
  }>;
}

/**
 * Create purchase orders from plan result
 * Backend: POST /api/v1/tenants/{tenant_id}/procurement/plans/{plan_id}/create-purchase-orders
 */
export interface CreatePOsResult {
  success: boolean;
  created_pos: {
    po_id: string;
    po_number: string;
    supplier_id: string;
    items_count: number;
    total_amount: number;
  }[];
  failed_pos: {
    supplier_id: string;
    error: string;
  }[];
  total_created: number;
  total_failed: number;
}

/**
 * Link requirement to purchase order request
 * Backend: Used in requirement linking operations
 */
export interface LinkRequirementToPORequest {
  purchase_order_id: string;
  purchase_order_number: string;
  ordered_quantity: number;
  expected_delivery_date?: string;
}

/**
 * Update delivery status request
 * Backend: Used in delivery status updates
 */
export interface UpdateDeliveryStatusRequest {
  delivery_status: string;
  received_quantity?: number;
  actual_delivery_date?: string;
  quality_rating?: number;
}

/**
 * Approval request
 * Backend: Used in plan approval operations
 */
export interface ApprovalRequest {
  approval_notes?: string;
}

/**
 * Rejection request
 * Backend: Used in plan rejection operations
 */
export interface RejectionRequest {
  rejection_notes?: string;
}

/**
 * Paginated procurement plans
 * Backend: GET /api/v1/tenants/{tenant_id}/procurement/plans
 */
export interface PaginatedProcurementPlans {
  plans: ProcurementPlanResponse[];
  total: number;
  page: number;
  limit: number;
  has_more: boolean;
}

/**
 * Forecast request
 * Backend: Used in forecasting operations
 */
export interface ForecastRequest {
  target_date: string;
  horizon_days: number;
  include_confidence_intervals: boolean;
  product_ids?: string[];
}

// ================================================================
// QUERY PARAMETER TYPES
// ================================================================

/**
 * Get procurement plans query parameters
 * Backend: GET /api/v1/tenants/{tenant_id}/procurement/plans
 */
export interface GetProcurementPlansParams {
  tenant_id: string;
  status?: string;
  start_date?: string;
  end_date?: string;
  limit?: number;
  offset?: number;
}

/**
 * Get plan requirements query parameters
 * Backend: GET /api/v1/tenants/{tenant_id}/procurement/plans/{plan_id}/requirements
 */
export interface GetPlanRequirementsParams {
  tenant_id: string;
  plan_id: string;
  status?: string;
  priority?: string;
}

/**
 * Update plan status parameters
 * Backend: PATCH /api/v1/tenants/{tenant_id}/procurement/plans/{plan_id}/status
 */
export interface UpdatePlanStatusParams {
  tenant_id: string;
  plan_id: string;
  status: PlanStatus;
  notes?: string;
}
