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

/**
 * [BIZ_FIN_50] 跨主权多币种对冲对账引擎 (Multi-Currency Recon)
 * @description 处理汇率波动导致的对账偏差，自动对冲平衡。
 */
export class MultiCurrencyHedgingReconService {
  private static readonly RECON_TABLE = 'cf_fx_recon_records';

  /**
   * 执行对冲对账
   */
  static async performFXRecon(tenantId: string, orderId: string) {
    logger.info(`[FXRecon] Performing FX reconciliation for order: ${orderId}`);

    // 1. 获取订单数据
    const order = await db('cf_consumer_orders').where({ tenant_id: tenantId, order_id: orderId }).first();
    if (!order) return null;

    // 2. 获取下单时的汇率与当前汇率 (联动 CurrencyRiskService)
    const baseCurrency = 'USD';
    const orderCurrency = order.currency;
    const orderAmount = Number(order.total_amount);

    // 模拟汇率数据
    const orderRate = 0.92; // 下单时 1 USD = 0.92 EUR
    const currentRate = 0.88; // 当前 1 USD = 0.88 EUR (汇率剧烈波动)

    const expectedFiat = orderAmount / orderRate;
    const actualFiat = orderAmount / currentRate;
    const fxDrift = actualFiat - expectedFiat;

    // 3. 记录对账偏差并生成对冲建议
    const reconRecord = {
      id: `FXR-${orderId}-${Date.now()}`,
      tenant_id: tenantId,
      order_id: orderId,
      base_currency: baseCurrency,
      order_currency: orderCurrency,
      order_amount: orderAmount,
      order_rate: orderRate,
      current_rate: currentRate,
      fx_drift: Number(fxDrift.toFixed(4)),
      status: Math.abs(fxDrift) > 5 ? 'DISCREPANCY' : 'MATCHED',
      created_at: new Date()
    };

    await db(this.RECON_TABLE).insert(reconRecord);

    if (reconRecord.status === 'DISCREPANCY') {
      logger.warn(`[FXRecon] Significant FX drift detected for order ${orderId}: ${fxDrift} USD. Recommending HEDGING.`);
    }

    return reconRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.RECON_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.RECON_TABLE} table...`);
      await db.schema.createTable(this.RECON_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.string('base_currency', 10);
        table.string('order_currency', 10);
        table.decimal('order_amount', 15, 2);
        table.decimal('order_rate', 10, 6);
        table.decimal('current_rate', 10, 6);
        table.decimal('fx_drift', 15, 4);
        table.string('status', 32);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'order_id']);
      });
    }
  }
}
