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

export interface CurrencyBalance {
  currency: string;
  amount: number;
  usdEquivalent: number;
}

/**
 * [BIZ_FIN_09] 多币种资金池自动对账与换汇建议服务
 * @description 实时汇总各平台币种资金，计算汇损风险并提供最优换汇建议
 */
export class MultiCurrencyFinanceService {
  /**
   * 汇总租户全平台币种余额
   */
  static async getGlobalBalances(tenantId: string): Promise<CurrencyBalance[]> {
    logger.info(`[MultiCurrency] Fetching global balances for Tenant: ${tenantId}`);

    // 1. 从订单与对账表中聚合已结算资金
    const balances = await db('cf_orders')
      .where({ tenant_id: tenantId, status: 'RECONCILED' })
      .select('currency')
      .sum('selling_price as total_amount')
      .groupBy('currency');

    const results: CurrencyBalance[] = [];

    for (const b of balances) {
      // 2. 获取实时汇率进行价值折算
      const rate = await FXHedgingService.getDynamicSafetyMargin(b.currency + '/USD'); 
      // 注意：此处简化使用 safety margin 逻辑，实际应调用汇率 API
      const usdEquivalent = b.total_amount * (1 / 7.2); // 模拟汇率

      results.push({
        currency: b.currency,
        amount: Number(b.total_amount),
        usdEquivalent
      });
    }

    return results;
  }

  /**
   * 生成自动换汇建议 (BIZ_FIN_09)
   */
  static async generateExchangeAdvice(tenantId: string): Promise<any> {
    const balances = await this.getGlobalBalances(tenantId);
    
    // 逻辑：如果某非 USD 币种余额超过 $5000 且汇率波动剧增，建议换汇
    const highRiskBalances = balances.filter(b => b.currency !== 'USD' && b.usdEquivalent > 5000);

    return highRiskBalances.map(b => ({
      tenantId,
      fromCurrency: b.currency,
      toCurrency: 'USD',
      amount: b.amount,
      reason: `High exposure in ${b.currency} (${b.usdEquivalent.toFixed(2)} USD). Strategic exchange suggested to lock profits.`
    }));
  }
}
