/**
 * 🎯 Interface Route - Definição da entidade Rota PraFrota
 * 
 * Interface principal para gerenciamento de rotas seguindo os padrões
 * definidos na documentação técnica do módulo de rotas.
 * 
 * ✨ Suporta diferentes tipos de rotas:
 * - First Mile: Coleta em centros de distribuição
 * - Line Haul: Transporte entre cidades/regiões
 * - Last Mile: Entrega final ao cliente
 * - Custom: Rotas personalizadas
 */

export interface Route {
  // ========================================
  // 🆔 IDENTIFICAÇÃO
  // ========================================
  Id: string; 
  routeNumber: string;
  companyId: string;
  company_name?: string; // Nome da empresa
  icon_logo?: string; // URL do logo da empresa ou null para usar iniciais
  customerId?: string;
  customer_name?: string; // Nome do cliente
  contractId?: string;
  contractName?: string; // Nome do contrato
  freightTableId?: string;
  freightTableName?: string; // Nome da tabela de preços

  // ========================================
  // 📋 INFORMAÇÕES BÁSICAS
  // ========================================
  type: 'firstMile' | 'lineHaul' | 'lastMile' | 'custom';
  status: 'pending' | 'inProgress' | 'completed' | 'delayed' | 'cancelled';
  priority: 'low' | 'normal' | 'high' | 'urgent';
  description?: string;
  notes?: string;

  // ========================================
  // 📍 LOCALIZAÇÃO E ROTA
  // ========================================
  origin: RouteLocation;
  destination: RouteLocation;
  currentLocation?: RouteLocation;
  stops?: RouteStop[];
  
  // Dados de distância e duração
  totalDistance?: number; // em km
  estimatedDuration?: number; // em minutos
  actualDuration?: number; // em minutos
  
  // ✨ Novos campos de controle de programado vs realizado
  plannedKm?: number; // KM Programado
  actualKm?: number; // KM Realizado
  plannedDuration?: number; // Duração Programada (em minutos)
  actualDurationComplete?: number; // Duração Realizada (em minutos)

  // ========================================
  // ⏰ CRONOGRAMA
  // ========================================
  scheduledDeparture: Date;
  actualDeparture?: Date;
  scheduledArrival: Date;
  actualArrival?: Date;
  
  // ========================================
  // 🚛 RECURSOS ALOCADOS
  // ========================================
  driverId?: string;
  driverName?: string;
  driverRating?: number; // Rating do motorista de 1-5
  vehicleId?: string;
  vehiclePlate?: string;
  vehicleType?: string;

  // ========================================
  // 📦 CARGA E PRODUTOS
  // ========================================
  productType?: string;
  estimatedPackages?: number;
  actualPackages?: number;
  cargoValue?: number; // Valor da carga transportada (R$)
  weight?: number; // Peso da carga (kg)
  totalWeight?: number; // em kg
  totalVolume?: number; // em m³
  
  // Informações específicas de marketplace
  marketplace?: 'mercadolivre' | 'shopee' | 'amazon' | 'custom';
  externalOrderId?: string;
  
  // ========================================
  // 💰 FINANCEIRO
  // ========================================
  totalValue: number;
  paidValue?: number; // ✨ Valor Pago (pode ser diferente do valor total)
  costPerKm?: number;
  fuelCost?: number;
  tollCost?: number;
  driverPayment?: number;
  additionalCosts?: number;
  
  // ========================================
  // 📊 PERFORMANCE E MÉTRICAS
  // ========================================
  onTimeDelivery?: boolean;
  customerRating?: number; // 1-5
  deliveryAttempts?: number;
  averageSpeed?: number; // km/h
  fuelConsumption?: number; // litros
  
  // ========================================
  // 🔔 ALERTAS E NOTIFICAÇÕES
  // ========================================
  alerts?: RouteAlert[];
  notifications?: RouteNotification[];
  
  // ========================================
  // 📄 DOCUMENTAÇÃO
  // ========================================
  documents?: RouteDocument[];
  photos?: string[]; // URLs das fotos
  signature?: string; // URL da assinatura de entrega
  
  // ========================================
  // 🗃️ METADADOS
  // ========================================
  createdAt: Date;
  updatedAt: Date;
  createdBy?: string;
  updatedBy?: string;
  version?: number;
  
  // Campos específicos para integração com sistemas externos
  externalId?: string;
  syncStatus?: 'pending' | 'synced' | 'error';
  lastSync?: Date;
}

// ========================================
// 🏢 INTERFACES AUXILIARES
// ========================================

export interface RouteLocation {
  address: string;
  city: string;
  state: string;
  zipCode?: string;
  country?: string;
  latitude?: number;
  longitude?: number;
  facility?: string; // Nome da instalação/centro de distribuição
  contactName?: string;
  contactPhone?: string;
  accessInstructions?: string;
}

export interface RouteStop {
  stopId: string;
  sequence: number;
  location: RouteLocation;
  type: 'pickup' | 'delivery' | 'rest' | 'fuel' | 'maintenance';
  scheduledTime: Date;
  actualTime?: Date;
  duration?: number; // em minutos
  packages?: number;
  status: 'pending' | 'completed' | 'skipped' | 'failed';
  notes?: string;
  photos?: string[];
  signature?: string;
}

export interface RouteAlert {
  alertId: string;
  type: 'delay' | 'route_deviation' | 'vehicle_issue' | 'weather' | 'traffic' | 'security';
  severity: 'low' | 'medium' | 'high' | 'critical';
  message: string;
  timestamp: Date;
  resolved?: boolean;
  resolvedAt?: Date;
  resolvedBy?: string;
}

export interface RouteNotification {
  notificationId: string;
  type: 'sms' | 'email' | 'push' | 'whatsapp';
  recipient: string;
  message: string;
  sentAt: Date;
  status: 'pending' | 'sent' | 'delivered' | 'failed';
  templateId?: string;
}

export interface RouteDocument {
  documentId: string;
  type: 'invoice' | 'receipt' | 'manifest' | 'insurance' | 'permit' | 'other';
  name: string;
  url: string;
  uploadedAt: Date;
  uploadedBy: string;
  size?: number; // em bytes
  mimeType?: string;
}

// ========================================
// 🔍 INTERFACES PARA FILTROS E BUSCA
// ========================================

export interface RouteFilters {
  page?: number;
  limit?: number;
  type?: string[];
  status?: string[];
  driverId?: string;
  vehicleId?: string;
  customerId?: string;
  search?: string;
  dateRange?: {
    start: string;
    end: string;
  };
  region?: string;
  marketplace?: string[];
  priority?: string[];
}

export interface RouteResponse {
  data: Route[];
  pagination: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
  source: 'backend' | 'fallback' | 'file';
  timestamp: string;
}

// ========================================
// 📊 INTERFACES PARA RELATÓRIOS
// ========================================

export interface RouteMetrics {
  totalRoutes: number;
  completedRoutes: number;
  onTimeDeliveryRate: number;
  averageDeliveryTime: number;
  totalDistance: number;
  totalRevenue: number;
  totalCosts: number;
  profitMargin: number;
  fuelEfficiency: number;
  customerSatisfaction: number;
}

export interface RouteStatistics {
  byType: { [key: string]: number };
  byStatus: { [key: string]: number };
  byRegion: { [key: string]: number };
  byMarketplace: { [key: string]: number };
  byMonth: { [key: string]: number };
}

// ========================================
// 🎯 TIPOS ESPECÍFICOS PARA COMPONENTES
// ========================================

export interface RouteLocationData {
  routeId: string;
  routeNumber: string;
  type: string;
  status: string;
  origin: RouteLocation;
  destination: RouteLocation;
  currentLocation?: RouteLocation;
  vehiclePlate?: string;
  driverName?: string;
  scheduledDeparture: Date;
  scheduledArrival: Date;
}

export interface RouteHistoryItem {
  timestamp: Date;
  event: string;
  description: string;
  location?: RouteLocation;
  user?: string;
  details?: any;
} 