/**
 * 🧠 Fuel Analytics Library - Interface Definitions
 * 📊 Biblioteca de Análise Inteligente de Consumo de Combustível
 * 
 * ✨ Centraliza todos os cálculos e análises de consumo
 * 🎯 Reutilizável em todo o sistema
 * 🚀 Preparada para Machine Learning e IA
 */

// ========================================
// 📋 INTERFACES BASE
// ========================================

export interface FuelRecord {
  id: number;
  personId: number;
  vehicleId: number;
  supplierId: number;
  companyId: number;
  code: string;
  status: string;
  lat: string;
  lon: string;
  gasStationBrand: string;
  value: string;
  odometer: number;
  date: string;
  personName: string;
  licensePlate: string;
  vehicleModel: string;
  supplierName: string;
  companyName: string;
  items: FuelItem[];
}

export interface FuelItem {
  productId: number;
  productName: string;
  productCode: string;
  value: string;
  quantity: string;
  liters?: string; // Fallback compatibility
}

// ========================================
// 📊 ANÁLISES POR PRODUTO/COMBUSTÍVEL
// ========================================

export interface ProductAnalysis {
  productName: string;
  totalValue: number;
  totalQuantity: number;
  avgPricePerLiter: number;
  count: number;
  percentage: number;
}

export interface EfficiencyAnalysis {
  productName: string;
  avgConsumption: number;
  bestEfficiency: number;
  worstEfficiency: number;
  samplesCount: number;
}

// ========================================
// 👨‍💼 ANÁLISES POR MOTORISTA
// ========================================

export interface DriverAnalysis {
  driverName: string;
  driverId: number;
  totalValue: number;
  totalQuantity: number;
  totalSupplies: number;
  avgConsumption: number;
  bestEfficiency: number;
  worstEfficiency: number;
  fuelBreakdown: ProductAnalysis[];
  performanceRating: 'excellent' | 'good' | 'average' | 'poor';
  // 🆕 Novos campos adicionados
  maxSingleValue: number;  // Maior valor R$ em um único abastecimento
  totalKilometers: number; // Total de KM percorridos
  trendsLast30Days: {
    valueChange: number;
    quantityChange: number;
    efficiencyChange: number;
  };
}

// ========================================
// 📅 ANÁLISES TEMPORAIS
// ========================================

export interface TimeGrouping {
  period: string;
  startDate: Date;
  endDate: Date;
  totalValue: number;
  totalQuantity: number;
  totalSupplies: number;
  avgConsumption: number;
  totalKilometers: number; // 🆕 Total de KM percorridos no período
  fuelBreakdown: ProductAnalysis[];
  topDrivers: DriverAnalysis[];
  topStations: StationAnalysis[];
}

export interface BiweeklyAnalysis extends TimeGrouping {
  weekNumber: number;
}

export interface MonthlyAnalysis extends TimeGrouping {
  month: number;
  year: number;
}

export interface YearlyAnalysis extends TimeGrouping {
  year: number;
  monthlyBreakdown: MonthlyAnalysis[];
}

// ========================================
// ⛽ ANÁLISES POR POSTO DE COMBUSTÍVEL
// ========================================

export interface StationAnalysis {
  stationName: string;
  stationBrand: string;
  supplierId: number;
  location: {
    lat: number;
    lon: number;
    address?: string;
  };
  totalValue: number;
  totalQuantity: number;
  totalSupplies: number;
  avgPricePerLiter: number;
  fuelBreakdown: ProductAnalysis[];
  frequencyScore: number; // 0-100 score for heat map
  lastSupplyDate: Date;
  driverFrequency: { [driverId: number]: number };
}

// ========================================
// 🎯 ANÁLISES CONSOLIDADAS
// ========================================

export interface FuelSummary {
  totalProducts: number;
  totalValue: number;
  totalQuantity: number;
  totalSupplies: number;
  avgPricePerLiter: number;
  mostUsedFuel: string;
  mostEfficientDriver: string;
  mostFrequentStation: string;
  dateRange: {
    start: Date;
    end: Date;
    days: number;
  };
}

export interface ConsumptionAnalysis {
  avgConsumption: number;
  bestEfficiency: number;
  worstEfficiency: number;
  trend: 'improving' | 'stable' | 'worsening';
  samplesCount: number;
}

// ========================================
// 🔥 ANÁLISES AVANÇADAS (FUTURO ML/IA)
// ========================================

export interface PredictiveAnalysis {
  nextSupplyPrediction: {
    estimatedDate: Date;
    estimatedQuantity: number;
    estimatedValue: number;
    confidence: number; // 0-1
  };
  anomalyDetection: {
    unusualConsumption: boolean;
    unusualPrice: boolean;
    unusualLocation: boolean;
    score: number; // 0-1
  };
  recommendations: {
    betterStations: StationAnalysis[];
    efficiencyTips: string[];
    costSavingOpportunities: string[];
  };
}

export interface HeatMapData {
  stations: StationAnalysis[];
  bounds: {
    north: number;
    south: number;
    east: number;
    west: number;
  };
  clusters: {
    lat: number;
    lon: number;
    weight: number;
    stationCount: number;
  }[];
}

// ========================================
// 🎛️ CONFIGURAÇÕES DE ANÁLISE
// ========================================

export interface AnalyticsConfig {
  dateRange?: {
    start: Date;
    end: Date;
  };
  vehicleIds?: number[];
  driverIds?: number[];
  fuelTypes?: string[];
  stationIds?: number[];
  includeRejected?: boolean;
  groupBy?: 'day' | 'week' | 'biweekly' | 'month' | 'quarter' | 'year';
  sortBy?: 'date' | 'value' | 'quantity' | 'efficiency';
  sortOrder?: 'asc' | 'desc';
  limit?: number;
}

// ========================================
// 📈 INTERFACES PARA GRÁFICOS
// ========================================

export interface ChartDataPoint {
  label: string;
  value: number;
  color?: string;
  metadata?: any;
}

export interface ChartSeries {
  name: string;
  data: ChartDataPoint[];
  color?: string;
  type?: 'line' | 'bar' | 'area';
}

export interface MonthlyConsumptionChart {
  totalConsumption: {
    labels: string[];
    datasets: {
      label: string;
      data: number[];
      backgroundColor?: string;
      borderColor?: string;
    }[];
  };
  byFuelType: {
    labels: string[];
    datasets: {
      label: string;
      data: number[];
      backgroundColor?: string;
      borderColor?: string;
    }[];
  };
  summary: {
    totalMonths: number;
    totalValue: number;
    totalQuantity: number;
    avgMonthlyConsumption: number;
    peakMonth: {
      month: string;
      value: number;
      quantity: number;
    };
    lowMonth: {
      month: string;
      value: number;
      quantity: number;
    };
  };
}

// ========================================
// 📤 RESULTADO PRINCIPAL DA BIBLIOTECA
// ========================================

export interface FuelAnalyticsResult {
  summary: FuelSummary;
  consumption: ConsumptionAnalysis;
  products: ProductAnalysis[];
  efficiency: EfficiencyAnalysis[];
  drivers: DriverAnalysis[];
  temporal: {
    biweekly: BiweeklyAnalysis[];
    monthly: MonthlyAnalysis[];
    yearly: YearlyAnalysis[];
  };
  stations: StationAnalysis[];
  heatMap: HeatMapData;
  predictive?: PredictiveAnalysis; // Opcional - futuro ML
  config: AnalyticsConfig;
  generatedAt: Date;
  processingTime: number; // ms
}
