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

/**
 * [BIZ_FIN_189] 异常低毛利订单强制拦截建议 (Low Margin)
 * @description 实时识别低毛利订单，拦截配置错误。
 */
export class MarginProtector {
  private static readonly INTERCEPTOR_TABLE = 'cf_margin_interceptor_logs';

  /**
   * 拦截低毛利订单
   */
  static async interceptLowMarginOrder(tenantId: string, orderId: string) {
    logger.info(`[MarginProtector] Intercepting low margin order: ${orderId} for tenant: ${tenantId}`);

    // 1. 获取对账数据中的净利
    const recon = await db('cf_recon_records').where({ orderId, tenantId }).first();
    if (!recon) return null;

    // 2. 识别低毛利 (净利 < 收入的 10%)
    const marginRatio = recon.platformAmount > 0 ? recon.netProfit / recon.platformAmount : 0;
    let isIntercepted = false;
    let actionReason = 'Normal margin';

    if (marginRatio < 0.1) {
      isIntercepted = true;
      actionReason = `Low margin detected (${(marginRatio * 100).toFixed(2)}%). Below 10% threshold.`;
    }

    const log = {
      id: `MP-${tenantId}-${orderId}`,
      tenantId,
      orderId,
      marginRatio: Number(marginRatio.toFixed(4)),
      isIntercepted,
      actionReason,
      created_at: new Date()
    };

    // 3. 存储拦截记录
    await db(this.INTERCEPTOR_TABLE)
      .insert(log)
      .onConflict(['id'])
      .merge();

    return log;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.INTERCEPTOR_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.INTERCEPTOR_TABLE} table...`);
      await db.schema.createTable(this.INTERCEPTOR_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.decimal('marginRatio', 5, 4);
        table.boolean('isIntercepted').notNullable();
        table.text('actionReason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'orderId']);
      });
    }
  }
}
