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

export interface FreightBill {
  id: string;
  tenantId: string;
  orderId: string;
  trackingNumber: string;
  carrier: string;
  estimatedCost: number;
  actualCost: number;
  status: 'MATCHED' | 'DISCREPANCY' | 'PENDING';
  discrepancyReason?: string;
  billDate: Date;
}

export interface FreightHeatmap {
  origin: string;
  destination: string;
  avgCostPerKg: number;
  minCostPerKg: number;
  maxCostPerKg: number;
  carrierCount: number;
}

/**
 * [BIZ_LOG_12] 智能货代比价与运费账单审计 (Freight Audit)
 * @description 核心逻辑：建立货代费率热力图，自动审计承运商账单并核销，防止超支。
 */
export class FreightAuditService {
  private static readonly BILL_TABLE = 'cf_freight_bills';
  private static readonly RATE_HISTORY_TABLE = 'cf_freight_rate_history';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasBillTable = await db.schema.hasTable(this.BILL_TABLE);
    if (!hasBillTable) {
      logger.info(`📦 Creating ${this.BILL_TABLE} table...`);
      await db.schema.createTable(this.BILL_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenantId', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.string('trackingNumber', 64).notNullable();
        table.string('carrier', 64).notNullable();
        table.decimal('estimatedCost', 15, 2);
        table.decimal('actualCost', 15, 2);
        table.string('status', 20).notNullable();
        table.text('discrepancyReason');
        table.timestamp('billDate').defaultTo(db.fn.now());
        table.timestamps(true, true);
        table.index(['tenantId', 'orderId']);
        table.index(['trackingNumber']);
      });
    }

    const hasRateTable = await db.schema.hasTable(this.RATE_HISTORY_TABLE);
    if (!hasRateTable) {
      logger.info(`📦 Creating ${this.RATE_HISTORY_TABLE} table...`);
      await db.schema.createTable(this.RATE_HISTORY_TABLE, (table) => {
        table.increments('id').primary();
        table.string('carrier', 64).notNullable();
        table.string('origin', 50).notNullable();
        table.string('destination', 50).notNullable();
        table.decimal('costPerKg', 10, 2).notNullable();
        table.string('currency', 10).defaultTo('USD');
        table.timestamp('effectiveDate').defaultTo(db.fn.now());
        table.timestamps(true, true);
        table.index(['origin', 'destination', 'carrier']);
      });
    }
  }

  /**
   * 提交并审计货代账单
   */
  static async auditBill(bill: Omit<FreightBill, 'status' | 'discrepancyReason'>): Promise<FreightBill> {
    logger.info(`[FreightAudit] Auditing bill for Order: ${bill.orderId}, Carrier: ${bill.carrier}`);

    // 1. 获取预估成本 (来自 GlobalFulfillmentService)
    const fulfillment = await db('cf_global_fulfillment').where({ order_id: bill.orderId }).first();
    const estimatedCost = fulfillment ? fulfillment.estimated_cost : bill.estimatedCost;

    // 2. 差异识别 (Tolerance: 5%)
    let status: FreightBill['status'] = 'MATCHED';
    let discrepancyReason = '';

    const diff = bill.actualCost - estimatedCost;
    const diffPercent = (diff / (estimatedCost || 1)) * 100;

    if (Math.abs(diffPercent) > 5) {
      status = 'DISCREPANCY';
      discrepancyReason = `Cost deviation: ${diffPercent.toFixed(2)}% (Actual: ${bill.actualCost}, Est: ${estimatedCost})`;
      logger.warn(`[FreightAudit] DISCREPANCY detected for ${bill.orderId}: ${discrepancyReason}`);
    }

    const finalBill: FreightBill = {
      ...bill,
      estimatedCost,
      status,
      discrepancyReason
    };

    // 3. 持久化账单
    await db(this.BILL_TABLE)
      .insert({
        ...finalBill,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['id'])
      .merge();

    // 4. 更新费率历史 (用于热力图分析)
    // 假设账单中有重量信息 (此处简化，从订单或履行记录获取)
    const order = await db('cf_consumer_orders').where({ id: bill.orderId }).first();
    if (order && order.weight_kg > 0) {
      await db(this.RATE_HISTORY_TABLE).insert({
        carrier: bill.carrier,
        origin: 'CN', // 默认中国发货，实际应从订单获取
        destination: order.country_code,
        costPerKg: bill.actualCost / order.weight_kg,
        currency: 'USD',
        effectiveDate: bill.billDate,
        created_at: new Date(),
        updated_at: new Date()
      });
    }

    return finalBill;
  }

  /**
   * 获取费率热力图数据
   */
  static async getRateHeatmap(origin: string, destination: string): Promise<FreightHeatmap> {
    const stats = await db(this.RATE_HISTORY_TABLE)
      .where({ origin, destination })
      .andWhere('effectiveDate', '>=', db.raw('DATE_SUB(NOW(), INTERVAL 30 DAY)'))
      .select(
        db.raw('AVG(costPerKg) as avgCost'),
        db.raw('MIN(costPerKg) as minCost'),
        db.raw('MAX(costPerKg) as maxCost'),
        db.raw('COUNT(DISTINCT carrier) as carriers')
      )
      .first();

    return {
      origin,
      destination,
      avgCostPerKg: Number(stats.avgCost || 0).toFixed(2) as any,
      minCostPerKg: Number(stats.minCost || 0).toFixed(2) as any,
      maxCostPerKg: Number(stats.maxCost || 0).toFixed(2) as any,
      carrierCount: stats.carriers || 0
    };
  }
}
