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

/**
 * [BIZ_FIN_192] 多平台提现手续费阶梯优化建议 (Payout)
 * @description 推荐最佳提现额度，优化阶梯提现手续费。
 */
export class PayoutOptimizer {
  private static readonly OPTIMIZER_TABLE = 'cf_payout_optimizations';

  /**
   * 优化提现策略
   */
  static async optimizePayout(tenantId: string, platform: string, balance: number) {
    logger.info(`[PayoutOptimizer] Optimizing payout for platform: ${platform} for tenant: ${tenantId}`);

    // 1. 获取平台的阶梯提现费率数据 (模拟)
    const tiers = [
      { min: 0, max: 1000, feeRatio: 0.015 },
      { min: 1001, max: 5000, feeRatio: 0.012 },
      { min: 5001, max: 20000, feeRatio: 0.01 },
      { min: 20001, max: Infinity, feeRatio: 0.008 }
    ];

    const currentTier = tiers.find(t => balance >= t.min && balance <= t.max);
    if (!currentTier) return null;

    // 2. 识别更优阶梯 (如果余额接近下一阶梯)
    const nextTier = tiers.find(t => t.min > balance);
    let suggestion = 'PAYOUT_NOW';
    let recommendation = `Current balance is in ${currentTier.feeRatio * 100}% fee tier. Recommended to payout.`;

    if (nextTier && (nextTier.min - balance) / balance < 0.2) { // 如果余额在下一阶梯的 20% 以内
      suggestion = 'WAIT_FOR_NEXT_TIER';
      recommendation = `Wait for balance to reach $${nextTier.min} to drop fee to ${nextTier.feeRatio * 100}%.`;
    }

    const optimization = {
      id: `PO-${tenantId}-${platform}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      platform,
      currentBalance: Number(balance),
      currentFeeRatio: Number(currentTier.feeRatio.toFixed(4)),
      suggestion,
      recommendation,
      created_at: new Date()
    };

    // 3. 存储优化建议
    await db(this.OPTIMIZER_TABLE)
      .insert(optimization)
      .onConflict(['id'])
      .merge();

    return optimization;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.OPTIMIZER_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.OPTIMIZER_TABLE} table...`);
      await db.schema.createTable(this.OPTIMIZER_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('platform', 64).notNullable();
        table.decimal('currentBalance', 15, 2);
        table.decimal('currentFeeRatio', 5, 4);
        table.string('suggestion', 20); // E.g., PAYOUT_NOW, WAIT_FOR_NEXT_TIER
        table.text('recommendation');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'platform']);
      });
    }
  }
}
