/**
 * TypeScript interfaces for all Unified Wizard data structures
 *
 * This file provides type safety for wizard form data across all sub-wizards.
 * Each interface represents the complete data structure for a specific wizard type.
 */

// ============================================================================
// Common Types
// ============================================================================

export type MeasurementUnit = 'kg' | 'g' | 'l' | 'ml' | 'units' | 'dozen' | 'lb' | 'oz';

export type IngredientCategory =
  | 'flour'
  | 'dairy'
  | 'eggs'
  | 'fats'
  | 'sweeteners'
  | 'additives'
  | 'fruits'
  | 'nuts'
  | 'spices'
  | 'leavening';

export type ProductCategory = 'bread' | 'pastry' | 'cake' | 'cookies' | 'specialty';

export type ProductType = 'ingredient' | 'finished_product';

export type SupplierType = 'local' | 'national' | 'international' | 'distributor' | 'manufacturer';

export type SupplierStatus = 'active' | 'inactive' | 'pending';

export type EquipmentType = 'oven' | 'mixer' | 'proofer' | 'refrigerator' | 'other';

export type QualityCheckType =
  | 'visual'
  | 'weight'
  | 'temperature'
  | 'texture'
  | 'taste'
  | 'moisture'
  | 'shelf-life';

export type CustomerType = 'individual' | 'business' | 'central_bakery' | 'RETAIL' | 'WHOLESALE' | 'RESTAURANT' | 'HOTEL' | 'ENTERPRISE';

export type CustomerSegment = 'vip' | 'regular' | 'wholesale';

export type PriorityLevel = 'low' | 'medium' | 'high';

export type DeliveryMethod = 'pickup' | 'delivery' | 'shipping';

export type OrderStatus =
  | 'draft'
  | 'confirmed'
  | 'in_production'
  | 'ready'
  | 'delivered'
  | 'cancelled';

export type PaymentStatus = 'pending' | 'partial' | 'paid' | 'overdue';

export type EmploymentType = 'full-time' | 'part-time' | 'contractor';

export type Position = 'baker' | 'pastry-chef' | 'manager' | 'sales' | 'delivery';

export type SalesEntryMethod = 'manual' | 'upload';

export type PaymentMethod = 'cash' | 'card' | 'transfer' | 'check';

// ============================================================================
// Inventory Wizard Data
// ============================================================================

export interface InventoryWizardData {
  // Step 1: Product Type
  productType?: ProductType;
  sku?: string;
  barcode?: string;
  brand?: string;

  // Step 2: Basic Info
  name?: string;
  ingredientCategory?: IngredientCategory;
  productCategory?: ProductCategory;
  description?: string;
  packageSize?: string;
  isPerishable?: boolean;
  shelfLifeDays?: number;
  allergenInfo?: string;

  // Step 3: Stock Configuration
  unitOfMeasure?: MeasurementUnit;
  standardCost?: number;
  lowStockThreshold?: number;
  reorderPoint?: number;
  reorderQuantity?: number;
  maxStockLevel?: number;
  leadTimeDays?: number;
}

// ============================================================================
// Supplier Wizard Data
// ============================================================================

export interface SupplierWizardData {
  // Basic Information
  name?: string;
  supplierCode?: string;
  supplierType?: SupplierType;
  status?: SupplierStatus;

  // Contact Information
  contactName?: string;
  email?: string;
  phone?: string;

  // Payment & Terms
  paymentTerms?: string;
  currency?: string;
  standardLeadTime?: number;

  // Advanced Options
  address?: string;
  city?: string;
  state?: string;
  postalCode?: string;
  country?: string;
  website?: string;
  taxId?: string;
  certifications?: string; // Comma-separated
  specializations?: string; // Comma-separated
  notes?: string;
  isPreferred?: boolean;
  autoApproveOrders?: boolean;
}

// ============================================================================
// Recipe Wizard Data
// ============================================================================

export interface RecipeIngredient {
  id: string;
  ingredientId: string;
  quantity: number;
  unit: MeasurementUnit;
  notes: string;
  order: number;
}

export interface RecipeWizardData {
  // Step 1: Recipe Details
  name?: string;
  recipeCode?: string;
  category?: ProductCategory;
  description?: string;
  finishedProductId?: string;
  yieldQuantity?: number;
  yieldUnit?: MeasurementUnit;
  prepTime?: number;
  bakingTime?: number;
  coolingTime?: number;
  isSeasonal?: boolean;
  seasonalStartMonth?: number;
  seasonalEndMonth?: number;
  isSignature?: boolean;
  targetEnvironmentTemp?: number;
  targetEnvironmentHumidity?: number;
  targetMargin?: number;

  // Step 2: Ingredients
  ingredients?: RecipeIngredient[];

  // Step 3: Quality Templates (Optional)
  qualityCheckId?: string;
  enableQualityChecks?: boolean;
  qualityConfig?: any; // JSONB
}

// ============================================================================
// Equipment Wizard Data
// ============================================================================

export interface EquipmentWizardData {
  name?: string;
  equipmentType?: EquipmentType;
  brand?: string;
  model?: string;
  location?: string;
  purchaseDate?: string; // ISO date string
  maintenanceIntervalDays?: number;
  notes?: string;
}

// ============================================================================
// Quality Template Wizard Data
// ============================================================================

export interface QualityTemplateWizardData {
  name?: string;
  checkType?: QualityCheckType;
  weight?: number; // 0-10
  scoringMethod?: string;
  passThreshold?: number;
  frequencyDays?: number;
  checkPoints?: any; // JSON array
  parameters?: any; // JSONB
  thresholds?: any; // JSONB
  scoringCriteria?: any; // JSONB
  acceptanceCriteria?: any; // JSONB
  responsibleRole?: string;
  requiredEquipment?: string;
  requiresPhoto?: boolean;
  isCriticalControlPoint?: boolean;
  notifyOnFailure?: boolean;
  description?: string;
}

// ============================================================================
// Customer Order Wizard Data
// ============================================================================

export interface OrderItem {
  productId: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  notes?: string;
}

export interface CustomerOrderWizardData {
  // Step 1: Customer Selection
  customer?: any; // Customer object from DB
  showNewCustomerForm?: boolean;
  newCustomerName?: string;
  newCustomerEmail?: string;
  newCustomerPhone?: string;
  newCustomerType?: CustomerType;

  // Step 2: Order Items
  orderItems?: OrderItem[];

  // Step 3: Delivery & Payment
  requestedDeliveryDate?: string; // ISO date string
  deliveryMethod?: DeliveryMethod;
  deliveryAddress?: string;
  deliveryCity?: string;
  deliveryState?: string;
  deliveryPostalCode?: string;
  deliveryInstructions?: string;

  // Advanced Options - Pricing
  discountAmount?: number;
  deliveryFee?: number;
  taxRate?: number;

  // Advanced Options - Production
  productionScheduledDate?: string;
  productionNotes?: string;

  // Advanced Options - Fulfillment
  fulfillmentStatus?: string;
  fulfillmentNotes?: string;

  // Advanced Options - Source & Channel
  orderSource?: string;
  orderChannel?: string;

  // Advanced Options - Notes & Communication
  internalNotes?: string;
  customerNotes?: string;
  packagingInstructions?: string;
  specialRequests?: string;
  allergyWarnings?: string;

  // Advanced Options - Notifications
  sendEmailConfirmation?: boolean;
  sendSMSNotifications?: boolean;
  customerEmail?: string;
  customerPhone?: string;

  // Advanced Options - Quality
  qualityRequirements?: string;

  // Advanced Options - Recurring
  isRecurring?: boolean;
  recurringFrequency?: string;

  // Advanced Options - Metadata
  tags?: string; // JSON array
  customFields?: any; // JSONB
}

// ============================================================================
// Customer Wizard Data
// ============================================================================

export interface CustomerWizardData {
  // Basic Information
  name?: string;
  customerCode?: string;
  customerType?: CustomerType;
  email?: string;
  phone?: string;

  // Business Details
  businessName?: string;
  taxId?: string;
  businessLicense?: string;

  // Payment & Credit
  paymentTerms?: string;
  creditLimit?: number;

  // Address
  address?: string;
  city?: string;
  state?: string;
  postalCode?: string;
  country?: string;

  // Customer Segmentation
  segment?: CustomerSegment;
  priority?: PriorityLevel;

  // Preferences
  preferredDeliveryMethod?: DeliveryMethod;
  specialInstructions?: string;
  notes?: string;
}

// ============================================================================
// Team Member Wizard Data
// ============================================================================

export interface TeamMemberWizardData {
  // Step 1: Member Details
  name?: string;
  email?: string;
  phone?: string;
  position?: Position;
  employmentType?: EmploymentType;
  hireDate?: string; // ISO date string
  hourlyRate?: number;
  notes?: string;

  // Step 2: Permissions
  role?: string;
  canManageInventory?: boolean;
  canViewRecipes?: boolean;
  canCreateOrders?: boolean;
  canViewFinancial?: boolean;
}

// ============================================================================
// Sales Entry Wizard Data
// ============================================================================

export interface SalesItem {
  productId: string;
  productName: string;
  quantity: number;
  unitPrice: number;
}

export interface SalesEntryWizardData {
  // Step 1: Entry Method
  entryMethod?: SalesEntryMethod;

  // Step 2a: Manual Entry
  saleDate?: string; // ISO date string
  paymentMethod?: PaymentMethod;
  salesItems?: SalesItem[];
  notes?: string;

  // Step 2b: File Upload
  uploadedFile?: File;
  validationResults?: {
    totalRows: number;
    validRows: number;
    errors: string[];
  };

  // Step 3: Review
  confirmedForSubmission?: boolean;
}

// ============================================================================
// Union Type for All Wizard Data
// ============================================================================

export type AnyWizardData =
  | InventoryWizardData
  | SupplierWizardData
  | RecipeWizardData
  | EquipmentWizardData
  | QualityTemplateWizardData
  | CustomerOrderWizardData
  | CustomerWizardData
  | TeamMemberWizardData
  | SalesEntryWizardData;

// ============================================================================
// Type Guards
// ============================================================================

export function isInventoryWizardData(data: any): data is InventoryWizardData {
  return data && ('productType' in data || 'unitOfMeasure' in data);
}

export function isSupplierWizardData(data: any): data is SupplierWizardData {
  return data && ('supplierType' in data || 'supplierCode' in data);
}

export function isRecipeWizardData(data: any): data is RecipeWizardData {
  return data && ('ingredients' in data || 'finishedProductId' in data);
}

export function isEquipmentWizardData(data: any): data is EquipmentWizardData {
  return data && 'equipmentType' in data;
}

export function isQualityTemplateWizardData(data: any): data is QualityTemplateWizardData {
  return data && 'checkType' in data;
}

export function isCustomerOrderWizardData(data: any): data is CustomerOrderWizardData {
  return data && ('orderItems' in data || 'deliveryMethod' in data);
}

export function isCustomerWizardData(data: any): data is CustomerWizardData {
  return data && ('customerCode' in data || 'customerType' in data);
}

export function isTeamMemberWizardData(data: any): data is TeamMemberWizardData {
  return data && ('position' in data || 'employmentType' in data);
}

export function isSalesEntryWizardData(data: any): data is SalesEntryWizardData {
  return data && 'entryMethod' in data;
}
