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

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

      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 || rerouteAdvice.reason,
          estimated_delay_reduction: delayReduction
        });

        // 审计记录
        await AuditService.log({
          tenantId: tenantId,
          action: 'LOGISTICS_CONGESTION_REROUTE',
          module: 'LOGISTICS',
          resourceType: 'LOGISTICS_ROUTE',
          resourceId: nodeId,
          traceId: traceId,
          userId: 'system',
          result: 'success',
          source: 'console',
          afterSnapshot: { congestionLevel, delayReduction },
          metadata: { rerouteAdvice: rerouteAdvice.description || rerouteAdvice.reason }
        });
      });
    }
  }

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