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

/**
 * [BIZ_TRADE_18] 全球物流拥堵预测与自适应绕路建议
 * 负责预测关键枢纽（如苏伊士运河、洛杉矶港等）的拥堵，并为受影响订单自动生成绕路建议
 */
export class CongestionFailoverService {
  /**
   * 分析拥堵并提供建议
   */
  static async analyzeAndReroute(tenantId: string, nodeId: string, traceId: string): Promise<void> {
    // 1. 获取该节点的实时拥堵度 (模拟调用 AI 流量感知服务)
    const congestionLevel = await AIService.getNodeCongestion(nodeId);
    
    // 2. 只有在严重拥堵 (Level > 0.8) 时触发
    if (congestionLevel > 0.8) {
      const rerouteAdvice = await AIService.generateRerouteAdvice(nodeId);
      const delayReduction = rerouteAdvice.estimatedDelayReduction;

      await db.transaction(async (trx) => {
        // 记录建议
        const [id] = await trx('cf_congestion_failover').insert({
          tenant_id: tenantId,
          node_id: nodeId,
          congestion_level: congestionLevel,
          reroute_advice: rerouteAdvice.description,
          estimated_delay_reduction: delayReduction
        });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'LOGISTICS_CONGESTION_REROUTE',
          target_type: 'LOGISTICS_ROUTE',
          target_id: nodeId,
          trace_id: traceId,
          new_data: JSON.stringify({ congestionLevel, delayReduction }),
          metadata: JSON.stringify({ rerouteAdvice: rerouteAdvice.description })
        });
      });
    }
  }

  /**
   * 获取租户所有拥堵绕路记录
   */
  static async getHistory(tenantId: string) {
    return await db('cf_congestion_failover')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
