import db from '../config/database';
import { logger } from '../utils/logger';

export interface ShippingRoute {
  id: string;
  tenantId: string;
  carrierName: string;
  routeType: 'AIR' | 'SEA' | 'LAND' | 'EXPRESS';
  estimatedDays: number;
  costPerKg: number;
  reliability: number; // 0-1
}

/**
 * [BIZ_LOG_03] 跨境物流时效预测与路由优化服务
 * @description 基于历史发货数据预测不同线路时效，动态推荐最优物流渠道
 */
export class LogisticsIntelligenceService {
  private static readonly TABLE_NAME = 'cf_logistics_routes';

  /**
   * 初始化物流线路表 (由 index.ts 调用，简化处理)
   */
  static async initTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      console.log(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('carrier_name', 128).notNullable();
        table.string('route_type', 32).notNullable();
        table.float('estimated_days');
        table.float('cost_per_kg');
        table.float('reliability');
        table.timestamps(true, true);
        table.index(['tenant_id']);
      });
      console.log(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * [BIZ_TRADE_07] 跨境物流最优路由算法
   * @description 动态计算最优承运商，支持基于包裹价值的自动保险建议
   */
  static async optimizeRoute(params: {
    tenantId: string;
    orderValue: number;
    destinationCountry: string;
    weightKg: number;
  }): Promise<any> {
    logger.info(`[Logistics] Optimizing route for Order Value: ${params.orderValue}`);

    // 1. 获取基础推荐
    const baseRoute = await this.recommendRoute({
      tenantId: params.tenantId,
      destinationCountry: params.destinationCountry,
      weightKg: params.weightKg,
      priority: params.orderValue > 100 ? 'SPEED' : 'COST'
    });

    // 2. 动态风控与保险建议 (BIZ_TRADE_07)
    let insuranceSuggested = false;
    if (params.orderValue > 200 || baseRoute.reliability < 0.9) {
      insuranceSuggested = true;
    }

    return {
      ...baseRoute,
      insuranceSuggested,
      estimatedTotalCost: baseRoute.costPerKg * params.weightKg + (insuranceSuggested ? params.orderValue * 0.01 : 0)
    };
  }

  /**
   * [BIZ_TRADE_06] 跨境物流动态调度
   * @description 实时感知承运商时效波动并动态调整权重
   */
  static async dynamicReschedule(carrierId: string, delayDays: number): Promise<void> {
    logger.warn(`[Logistics] Carrier ${carrierId} reported delay of ${delayDays} days. Rescheduling...`);

    // 降低该承运商的可靠性权重
    const route = await db(this.TABLE_NAME).where({ id: carrierId }).first();
    if (route) {
      const newReliability = Math.max(0.1, route.reliability - (delayDays * 0.05));
      await db(this.TABLE_NAME).where({ id: carrierId }).update({
        reliability: newReliability,
        updated_at: new Date()
      });
    }
  }

  /**
   * [BIZ_LOG_05] 推荐最优线路
   */
  static async recommendRoute(params: {
    tenantId: string;
    destinationCountry: string;
    weightKg: number;
    priority: 'SPEED' | 'COST';
  }): Promise<ShippingRoute> {
    logger.info(`[Logistics] Recommending route for ${params.destinationCountry} (Priority: ${params.priority})`);
    
    // 模拟从数据库获取推荐线路
    return {
      id: `ROUTE-${Date.now()}`,
      tenantId: params.tenantId,
      carrierName: 'DHL Express',
      routeType: 'AIR',
      estimatedDays: 3.5,
      costPerKg: 12.5,
      reliability: 0.98
    };
  }
}
