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

/**
 * [BIZ_FIN_185] 全球分销网络利润分成自动结算 (Split)
 * @description 自动结算分销网络中各层级的利润分成。
 */
export class CommissionService {
  private static readonly SETTLEMENT_TABLE = 'cf_commission_settlements';

  /**
   * 结算分销佣金
   */
  static async settleCommissions(tenantId: string, orderId: string) {
    logger.info(`[Commission] Settling commissions for order: ${orderId} for tenant: ${tenantId}`);

    // 1. 获取订单数据
    const order = await db('cf_consumer_orders').where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) return null;

    // 2. 获取订单关联的分销商 (基于订单元数据)
    const referralId = order.referral_id; // 假设订单记录了分销商 ID
    if (!referralId) return [];

    // 3. 计算佣金 (基于分销商等级)
    const referral = await db('cf_referrals').where({ id: referralId, tenant_id: tenantId }).first();
    const commissionRatio = referral ? referral.commission_ratio : 0.05; // 默认 5%

    const commissionAmount = order.total_amount * commissionRatio;

    const settlement = {
      id: `CS-${tenantId}-${orderId}-${referralId}`,
      tenantId,
      orderId,
      referralId,
      orderAmount: order.total_amount,
      commissionRatio: Number(commissionRatio.toFixed(4)),
      commissionAmount: Number(commissionAmount.toFixed(2)),
      status: 'PENDING',
      created_at: new Date()
    };

    // 4. 存储结算记录
    await db(this.SETTLEMENT_TABLE)
      .insert(settlement)
      .onConflict(['id'])
      .merge();

    return settlement;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.SETTLEMENT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.SETTLEMENT_TABLE} table...`);
      await db.schema.createTable(this.SETTLEMENT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.string('referralId', 64).notNullable();
        table.decimal('orderAmount', 15, 2);
        table.decimal('commissionRatio', 5, 4);
        table.decimal('commissionAmount', 15, 2);
        table.string('status', 20); // E.g., PENDING, PAID, CANCELED
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'orderId', 'referralId']);
      });
    }
  }
}
