export interface Product {
  pid: number;
  title: string;
  SKU: string;
  stock_quantity: number;
  price: string;  // numeric(15,3)
  regular_price: string;  // numeric(15,3)
  cost_price: string;  // numeric(15,3)
  barcode: string;
  vendor: string;
  vendor_reference: string;
  brand: string | 'Unbranded';
  categories: string[];
  tags: string[];
  options: Record<string, any>;
  image: string | null;
  moq: number;
  uom: number;
  visible: boolean;
  managing_stock: boolean;
  replenishable: boolean;
  created_at: string;
  updated_at: string;
  
  // New fields
  description?: string;
  preorder_count?: number;
  notions_inv_count?: number;
  harmonized_tariff_code?: string;
  notions_reference?: string;
  line?: string;
  subline?: string;
  artist?: string;
  rating?: number;
  reviews?: number;
  weight?: number;
  dimensions?: {
    length: number;
    width: number;
    height: number;
  };
  country_of_origin?: string;
  location?: string;
  total_sold?: number;
  baskets?: number;
  notifies?: number;
  date_last_sold?: string;
  
  // Metrics
  daily_sales_avg?: string;  // numeric(15,3)
  weekly_sales_avg?: string;  // numeric(15,3)
  monthly_sales_avg?: string;  // numeric(15,3)
  avg_quantity_per_order?: string;  // numeric(15,3)
  number_of_orders?: number;
  first_sale_date?: string;
  last_sale_date?: string;
  last_purchase_date?: string;
  days_of_inventory?: string;  // numeric(15,3)
  weeks_of_inventory?: string;  // numeric(15,3)
  reorder_point?: string;  // numeric(15,3)
  safety_stock?: string;  // numeric(15,3)
  avg_margin_percent?: string;  // numeric(15,3)
  total_revenue?: string;  // numeric(15,3)
  inventory_value?: string;  // numeric(15,3)
  cost_of_goods_sold?: string;  // numeric(15,3)
  gross_profit?: string;  // numeric(15,3)
  gmroi?: string;  // numeric(15,3)
  avg_lead_time_days?: string;  // numeric(15,3)
  first_received_date?: string;
  last_received_date?: string;
  abc_class?: string;
  stock_status?: string;
  turnover_rate?: string;  // numeric(15,3)
  current_lead_time?: string;  // numeric(15,3)
  target_lead_time?: string;  // numeric(15,3)
  lead_time_status?: string;
  reorder_qty?: number;
  overstocked_amt?: string;  // numeric(15,3)
}

// Type for product status (used for calculated statuses)
export type ProductStatus = "Critical" | "Reorder Soon" | "Healthy" | "Overstock" | "At Risk" | "New" | "Unknown";

// Represents data returned by the /metrics endpoint (from product_metrics table)
export interface ProductMetric {
    pid: number;
    sku: string;
    title: string;
    brand: string | null;
    vendor: string | null;
    imageUrl: string | null;
    isVisible: boolean;
    isReplenishable: boolean;
    lastCalculated: string | null;
    
    // Additional Product Fields
    barcode: string | null;
    vendorReference: string | null; // Supplier #
    notionsReference: string | null; // Notions #
    preorderCount: number | null;
    notionsInvCount: number | null;
    harmonizedTariffCode: string | null;
    line: string | null;
    subline: string | null; 
    artist: string | null;
    moq: number | null;
    rating: number | null;
    reviews: number | null;
    weight: number | null;
    dimensions: {
        length: number | null;
        width: number | null;
        height: number | null;
    } | null;
    // Individual dimension fields for backend compatibility
    length: number | null;
    width: number | null; 
    height: number | null;
    countryOfOrigin: string | null;
    location: string | null;
    baskets: number | null; // Number of times added to basket
    notifies: number | null; // Number of stock notifications
    
    // Current Status
    currentPrice: number | null;
    currentRegularPrice: number | null;
    currentCostPrice: number | null;
    currentStock: number;
    currentStockCost: number | null;
    currentStockRetail: number | null;
    currentStockGross: number | null;
    onOrderQty: number | null;
    onOrderCost: number | null;
    onOrderRetail: number | null;
    earliestExpectedDate: string | null; // Date as string
    
    // Historical Dates
    dateCreated: string | null;
    dateFirstReceived: string | null;
    dateLastReceived: string | null;
    dateFirstSold: string | null;
    dateLastSold: string | null;
    ageDays: number | null;
    
    // Rolling Period Metrics
    sales7d: number | null; 
    revenue7d: number | null;
    sales14d: number | null; 
    revenue14d: number | null;
    sales30d: number | null; 
    revenue30d: number | null;
    cogs30d: number | null; 
    profit30d: number | null;
    returnsUnits30d: number | null; 
    returnsRevenue30d: number | null;
    discounts30d: number | null; 
    grossRevenue30d: number | null;
    grossRegularRevenue30d: number | null;
    stockoutDays30d: number | null;
    sales365d: number | null; 
    revenue365d: number | null;
    avgStockUnits30d: number | null; 
    avgStockCost30d: number | null;
    avgStockRetail30d: number | null; 
    avgStockGross30d: number | null;
    receivedQty30d: number | null; 
    receivedCost30d: number | null;
    
    // Calculated KPIs
    asp30d: number | null; 
    acp30d: number | null; 
    avgRos30d: number | null;
    avgSalesPerDay30d: number | null; 
    avgSalesPerMonth30d: number | null;
    margin30d: number | null; 
    markup30d: number | null; 
    gmroi30d: number | null;
    stockturn30d: number | null; 
    returnRate30d: number | null;
    discountRate30d: number | null; 
    stockoutRate30d: number | null;
    markdown30d: number | null; 
    markdownRate30d: number | null;
    sellThrough30d: number | null; 
    avgLeadTimeDays: number | null;
    
    // Forecasting & Replenishment
    abcClass: string | null;
    salesVelocityDaily: number | null;
    configLeadTime: number | null;
    configDaysOfStock: number | null;
    configSafetyStock: number | null;
    planningPeriodDays: number | null;
    leadTimeForecastUnits: number | null;
    daysOfStockForecastUnits: number | null;
    planningPeriodForecastUnits: number | null;
    leadTimeClosingStock: number | null;
    daysOfStockClosingStock: number | null;
    replenishmentNeededRaw: number | null;
    replenishmentUnits: number | null;
    replenishmentCost: number | null;
    replenishmentRetail: number | null;
    replenishmentProfit: number | null;
    toOrderUnits: number | null;
    forecastLostSalesUnits: number | null;
    forecastLostRevenue: number | null;
    stockCoverInDays: number | null;
    poCoverInDays: number | null;
    sellsOutInDays: number | null;
    replenishDate: string | null;
    overstockedUnits: number | null;
    overstockedCost: number | null;
    overstockedRetail: number | null;
    isOldStock: boolean | null;
    
    // Yesterday
    yesterdaySales: number | null;
    
    // Growth Metrics (P3)
    salesGrowth30dVsPrev: number | null;
    revenueGrowth30dVsPrev: number | null;
    salesGrowthYoy: number | null;
    revenueGrowthYoy: number | null;
    
    // Demand Variability Metrics (P3)
    salesVariance30d: number | null;
    salesStdDev30d: number | null;
    salesCv30d: number | null;
    demandPattern: string | null;
    
    // Service Level Metrics (P5)
    fillRate30d: number | null;
    stockoutIncidents30d: number | null;
    serviceLevel30d: number | null;
    lostSalesIncidents30d: number | null;
    
    // Seasonality Metrics (P5)
    seasonalityIndex: number | null;
    seasonalPattern: string | null;
    peakSeason: string | null;
    
    // Lifetime Metrics
    lifetimeSales: number | null;
    lifetimeRevenue: number | null;
    lifetimeRevenueQuality: string | null;
    
    // First Period Metrics
    first7DaysSales: number | null;
    first7DaysRevenue: number | null;
    first30DaysSales: number | null;
    first30DaysRevenue: number | null;
    first60DaysSales: number | null;
    first60DaysRevenue: number | null;
    first90DaysSales: number | null;
    first90DaysRevenue: number | null;
    
    // Calculated status (added by frontend)
    status?: ProductStatus;
}

// Type for filter options returned by /metrics/filter-options
export interface ProductFilterOptions {
    vendors: string[];
    brands: string[];
    abcClasses: string[];
}

// Type for keys used in sorting/filtering (matching frontend state/UI)
export type ProductMetricColumnKey =
  | 'pid'
  | 'title'
  | 'sku'
  | 'barcode'
  | 'brand'
  | 'line'
  | 'subline'
  | 'artist'
  | 'vendor'
  | 'vendorReference'
  | 'notionsReference'
  | 'harmonizedTariffCode'
  | 'countryOfOrigin'
  | 'location'
  | 'moq'
  | 'weight'
  | 'length'
  | 'width'
  | 'height'
  | 'dimensions'
  | 'rating'
  | 'reviews'
  | 'baskets'
  | 'notifies'
  | 'preorderCount'
  | 'notionsInvCount'
  | 'isVisible'
  | 'isReplenishable'
  | 'abcClass'
  | 'status'
  | 'dateCreated'
  | 'currentStock'
  | 'currentStockCost'
  | 'currentStockRetail'
  | 'currentStockGross'
  | 'ageDays'
  | 'replenishDate'
  | 'planningPeriodDays'
  | 'currentPrice'
  | 'currentRegularPrice'
  | 'currentCostPrice'
  | 'configSafetyStock'
  | 'replenishmentUnits'
  | 'stockCoverInDays'
  | 'sellsOutInDays'
  | 'onOrderQty'
  | 'onOrderCost'
  | 'onOrderRetail'
  | 'earliestExpectedDate'
  | 'isOldStock'
  | 'overstockedUnits'
  | 'overstockedCost'
  | 'overstockedRetail'
  | 'stockoutDays30d'
  | 'stockoutRate30d'
  | 'avgStockUnits30d'
  | 'avgStockCost30d'
  | 'avgStockRetail30d'
  | 'avgStockGross30d'
  | 'receivedQty30d'
  | 'receivedCost30d'
  | 'configLeadTime'
  | 'configDaysOfStock'
  | 'poCoverInDays'
  | 'toOrderUnits'
  | 'replenishmentCost'
  | 'replenishmentRetail'
  | 'replenishmentProfit'
  | 'sales7d'
  | 'revenue7d'
  | 'sales14d'
  | 'revenue14d'
  | 'sales30d'
  | 'revenue30d'
  | 'sales365d'
  | 'revenue365d'
  | 'margin30d'
  | 'markup30d'
  | 'cogs30d'
  | 'profit30d'
  | 'gmroi30d'
  | 'stockturn30d'
  | 'sellThrough30d'
  | 'returnRate30d'
  | 'discountRate30d'
  | 'markdown30d'
  | 'markdownRate30d'
  | 'salesVelocityDaily'
  | 'yesterdaySales'
  | 'avgSalesPerDay30d'
  | 'avgSalesPerMonth30d'
  | 'returnsUnits30d'
  | 'returnsRevenue30d'
  | 'discounts30d'
  | 'grossRevenue30d'
  | 'grossRegularRevenue30d'
  | 'asp30d'
  | 'acp30d'
  | 'avgRos30d'
  | 'lifetimeSales'
  | 'lifetimeRevenue'
  | 'lifetimeRevenueQuality'
  | 'first7DaysSales'
  | 'first7DaysRevenue'
  | 'first30DaysSales'
  | 'first30DaysRevenue'
  | 'first60DaysSales'
  | 'first60DaysRevenue'
  | 'first90DaysSales'
  | 'first90DaysRevenue'
  | 'dateFirstReceived'
  | 'dateLastReceived'
  | 'dateFirstSold'
  | 'dateLastSold'
  | 'avgLeadTimeDays'
  | 'leadTimeForecastUnits'
  | 'daysOfStockForecastUnits'
  | 'planningPeriodForecastUnits'
  | 'leadTimeClosingStock'
  | 'daysOfStockClosingStock'
  | 'replenishmentNeededRaw'
  | 'forecastLostSalesUnits'
  | 'forecastLostRevenue'
  | 'salesGrowth30dVsPrev'
  | 'revenueGrowth30dVsPrev'
  | 'salesGrowthYoy'
  | 'revenueGrowthYoy'
  | 'salesVariance30d'
  | 'salesStdDev30d'
  | 'salesCv30d'
  | 'demandPattern'
  | 'fillRate30d'
  | 'stockoutIncidents30d'
  | 'serviceLevel30d'
  | 'lostSalesIncidents30d'
  | 'seasonalityIndex'
  | 'seasonalPattern'
  | 'peakSeason'
  | 'imageUrl';

export type ActiveFilterValue = FilterValue | FilterValueWithOperator;

export interface FilterValueWithOperator {
  value: FilterValue | string[] | number[];
  operator: ComparisonOperator;
}

export type FilterValue = string | number | boolean;

export type ComparisonOperator = 
  | "=" | "!=" | ">" | ">=" | "<" | "<=" | "between"
  | "contains" | "equals" | "starts_with" | "ends_with" | "not_contains"
  | "in" | "not_in" | "is_empty" | "is_not_empty" | "is_true" | "is_false";
