import db from '../config/database';
import { AuditService } from './AuditService';

/**
 * [BIZ_TRADE_14] 最后一公里配送成本优化模型
 * 负责在包裹妥投前，基于实时运力波动和承运商费率，自动优化配送路径
 */
export class LastMileOptimizerService {
  /**
   * 运行配送成本优化
   */
  static async optimizeOrderDelivery(
    tenantId: string,
    orderId: string,
    traceId: string
  ): Promise<{ carrier: string; savings: number }> {
    const order = await db('cf_orders').where({ id: orderId }).first();
    if (!order) throw new Error('Order not found');

    // 1. 获取备选承运商报价 (模拟调用不同承运商 API)
    const currentCarrier = order.platform === 'TikTok' ? 'Fulfillment by TikTok' : 'Standard Post';
    const originalCost = order.logistics_cost || 15.0; // 默认报价

    const carriers = [
      { name: 'Local Express V2', cost: 12.50, reliability: 0.98 },
      { name: 'FastDeliver AI', cost: 11.20, reliability: 0.95 },
      { name: 'EcoShipping', cost: 9.80, reliability: 0.90 }
    ];

    // 2. 选择最优承运商 (基于成本与可靠性加权)
    const bestCarrier = carriers.reduce((prev, curr) => {
      const prevScore = (1 / prev.cost) * prev.reliability;
      const currScore = (1 / curr.cost) * curr.reliability;
      return currScore > prevScore ? curr : prev;
    });

    const savings = originalCost - bestCarrier.cost;

    if (savings > 0) {
      // 3. 持久化优化记录
      await db.transaction(async (trx) => {
        await trx('cf_last_mile_optimization').insert({
          tenant_id: tenantId,
          order_id: orderId,
          optimized_carrier: bestCarrier.name,
          original_cost: originalCost,
          optimized_cost: bestCarrier.cost,
          savings,
          optimization_logic: JSON.stringify({ 
            alternatives: carriers, 
            selection_score: (1 / bestCarrier.cost) * bestCarrier.reliability 
          })
        });

        // 更新订单物流成本
        await trx('cf_orders')
          .where({ id: orderId })
          .update({
            logistics_cost: bestCarrier.cost,
            updated_at: db.fn.now()
          });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'LAST_MILE_OPTIMIZATION',
          target_type: 'ORDER',
          target_id: orderId,
          trace_id: traceId,
          new_data: JSON.stringify({ bestCarrier: bestCarrier.name, savings }),
          metadata: JSON.stringify({ originalCarrier: currentCarrier })
        });
      });

      return { carrier: bestCarrier.name, savings };
    }

    return { carrier: currentCarrier, savings: 0 };
  }

  /**
   * 汇总租户累计配送节省金额
   */
  static async getCumulativeSavings(tenantId: string): Promise<number> {
    const result = await db('cf_last_mile_optimization')
      .where({ tenant_id: tenantId })
      .sum('savings as total_savings')
      .first();
    return result?.total_savings || 0;
  }
}
