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

/**
 * [BIZ_FIN_162] 多币种自动锁汇避险建议 (FX Hedge)
 * @description 监控汇率波动，提供锁汇避险建议。
 */
export class CurrencyRiskService {
  private static readonly RISK_TABLE = 'cf_currency_risks';

  /**
   * 评估汇率风险
   */
  static async auditCurrencyRisk(tenantId: string, pair: string) {
    logger.info(`[CurrencyRisk] Auditing risk for pair: ${pair} for tenant: ${tenantId}`);

    // 1. 获取汇率趋势 (过去 30 天)
    const rates = await db('cf_fx_rates')
      .where({ pair })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .orderBy('created_at', 'desc');

    if (rates.length < 2) return null;

    const latestRate = Number(rates[0].rate);
    const avgRate = rates.reduce((acc, r) => acc + Number(rates[0].rate), 0) / rates.length;

    // 2. 识别风险 (波动率 > 2%)
    const volatility = Math.abs(latestRate - avgRate) / avgRate;
    let riskLevel = 'LOW';
    let suggestion = 'Monitor regularily';

    if (volatility > 0.05) {
      riskLevel = 'CRITICAL';
      suggestion = 'Extreme volatility detected. Hedge 100% of upcoming receivables immediately.';
    } else if (volatility > 0.02) {
      riskLevel = 'MEDIUM';
      suggestion = 'Moderate volatility. Consider hedging 50% of upcoming receivables.';
    }

    const riskRecord = {
      id: `CR-${tenantId}-${pair}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      pair,
      latestRate,
      volatility: Number(volatility.toFixed(4)),
      riskLevel,
      suggestion,
      created_at: new Date()
    };

    // 3. 存储风险记录
    await db(this.RISK_TABLE)
      .insert(riskRecord)
      .onConflict(['id'])
      .merge();

    return riskRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.RISK_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.RISK_TABLE} table...`);
      await db.schema.createTable(this.RISK_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('pair', 20).notNullable();
        table.decimal('latestRate', 15, 6);
        table.decimal('volatility', 10, 4);
        table.string('riskLevel', 20);
        table.text('suggestion');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'pair']);
      });
    }
  }
}
