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

/**
 * [BIZ_FIN_15] 全球多币种资金池实时平衡策略
 * 负责各币种余额的自动监控与平衡，避免单一币种短缺导致的支付失败或汇率风险
 */
export class FXRebalancingService {
  /**
   * 自动检查并触发余额平衡
   */
  static async autoBalance(tenantId: string, traceId: string): Promise<void> {
    // 1. 获取当前多币种余额 (模拟调用 MultiCurrencyFinanceService)
    const balances = await MultiCurrencyFinanceService.getBalances(tenantId);
    
    // 2. 识别短缺币种 (余额 < 阈值)
    const THRESHOLD = 1000; // 假设最低保留 1000 单位
    const shortCurrencies = balances.filter(b => b.amount < THRESHOLD);
    
    // 3. 识别富余币种 (余额 > 10倍阈值)
    const surplusCurrencies = balances.filter(b => b.amount > THRESHOLD * 10);

    if (shortCurrencies.length > 0 && surplusCurrencies.length > 0) {
      const from = surplusCurrencies[0];
      const to = shortCurrencies[0];
      const rebalanceAmount = 5000; // 假设固定平衡 5000 单位

      await db.transaction(async (trx) => {
        // 记录平衡意向
        const [id] = await trx('cf_fx_rebalancing').insert({
          tenant_id: tenantId,
          from_currency: from.currency,
          to_currency: to.currency,
          amount: rebalanceAmount,
          status: 'EXECUTED'
        });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'FX_POOL_REBALANCE',
          target_type: 'FINANCE_POOL',
          target_id: id.toString(),
          trace_id: traceId,
          new_data: JSON.stringify({ from: from.currency, to: to.currency, amount: rebalanceAmount }),
          metadata: JSON.stringify({ reason: 'Auto-balancing for short currency' })
        });
      });
    }
  }

  /**
   * 获取租户的余额平衡历史
   */
  static async getRebalancingHistory(tenantId: string) {
    return await db('cf_fx_rebalancing')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
