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

/**
 * [BIZ_FIN_175] 跨境汇款路径手续费选优建议 (Remit)
 * @description 对比 Wise, PingPong, Payoneer 等路径的手续费，推荐最佳汇款路径。
 */
export class RemitPathService {
  private static readonly PATH_TABLE = 'cf_remit_paths';

  /**
   * 对比汇款路径并给出建议
   */
  static async recommendRemitPath(tenantId: string, amount: number, currency: string) {
    logger.info(`[RemitPath] Recommending path for tenant: ${tenantId}, amount: ${amount} ${currency}`);

    // 1. 获取不同路径的模拟费率数据 (实际应调用各平台 API)
    const paths = [
      { name: 'Wise', feeRatio: 0.005, fixedFee: 2.0, speedDays: 1 },
      { name: 'PingPong', feeRatio: 0.007, fixedFee: 0, speedDays: 2 },
      { name: 'Payoneer', feeRatio: 0.01, fixedFee: 0, speedDays: 3 },
      { name: 'BankTransfer', feeRatio: 0, fixedFee: 25.0, speedDays: 5 }
    ];

    const recommendations = paths.map(path => {
      const estimatedFee = (amount * path.feeRatio) + path.fixedFee;
      const netAmount = amount - estimatedFee;

      return {
        id: `RM-${tenantId}-${path.name}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        pathName: path.name,
        currency,
        amount,
        estimatedFee: Number(estimatedFee.toFixed(2)),
        netAmount: Number(netAmount.toFixed(2)),
        speedDays: path.speedDays,
        recommendationScore: 0, // 稍后计算
        created_at: new Date()
      };
    });

    // 2. 评分逻辑 (手续费越低评分越高，速度越快加分)
    recommendations.sort((a, b) => a.estimatedFee - b.estimatedFee);
    
    // 给第一名打 100 分，以此类推
    recommendations.forEach((rec, idx) => {
      rec.recommendationScore = 100 - (idx * 20);
    });

    // 3. 存储建议记录
    for (const rec of recommendations) {
      await db(this.PATH_TABLE)
        .insert(rec)
        .onConflict(['id'])
        .merge();
    }

    return recommendations;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.PATH_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.PATH_TABLE} table...`);
      await db.schema.createTable(this.PATH_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('pathName', 64).notNullable();
        table.string('currency', 10).notNullable();
        table.decimal('amount', 15, 2);
        table.decimal('estimatedFee', 15, 2);
        table.decimal('netAmount', 15, 2);
        table.integer('speedDays');
        table.integer('recommendationScore');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId']);
      });
    }
  }
}
