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

/**
 * [BIZ_TRADE_16] 全球物流中断场景下的动态路由切换
 * 负责感知全球范围内的物流中断（如罢工、恶劣天气等），并自动切换备选路由
 */
export class FailoverLogisticsService {
  /**
   * 触发故障转移切换
   */
  static async triggerFailover(
    tenantId: string, 
    region: string, 
    originalCarrier: string, 
    reason: string,
    traceId: string
  ): Promise<void> {
    // 1. 获取备选承运商 (基于时效与可靠性评估)
    const failoverCarrier = await LogisticsIntelligenceService.getAlternativeCarrier(region, originalCarrier);
    
    // 2. 统计受影响的订单数量
    const affectedOrders = await db('cf_orders')
      .where({ tenant_id: tenantId, country_code: region, status: 'PENDING' })
      .count('* as count')
      .first();

    const count = affectedOrders?.count || 0;

    if (count > 0) {
      await db.transaction(async (trx) => {
        // 记录故障转移日志
        const [id] = await trx('cf_failover_logistics').insert({
          tenant_id: tenantId,
          disruption_region: region,
          original_carrier: originalCarrier,
          failover_carrier: failoverCarrier,
          reason,
          affected_orders_count: count
        });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'LOGISTICS_FAILOVER_TRIGGERED',
          target_type: 'LOGISTICS_FAILOVER',
          target_id: id.toString(),
          trace_id: traceId,
          new_data: JSON.stringify({ region, failoverCarrier, count }),
          metadata: JSON.stringify({ reason })
        });
      });
    }
  }

  /**
   * 获取租户所有故障转移历史
   */
  static async getFailoverHistory(tenantId: string) {
    return await db('cf_failover_logistics')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
