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

/**
 * [BIZ_FIN_179] 供应商佣金回扣/折扣追踪建议 (Rebate)
 * @description 追踪供应商回扣与折扣，优化采购成本。
 */
export class RebateService {
  private static readonly REBATE_TABLE = 'cf_supplier_rebates';

  /**
   * 追踪供应商回扣
   */
  static async trackSupplierRebates(tenantId: string, supplierId: string) {
    logger.info(`[Rebate] Tracking rebates for supplier: ${supplierId} for tenant: ${tenantId}`);

    // 1. 获取供应商的历史采购金额
    const stats = await db('cf_purchase_orders')
      .where({ tenant_id: tenantId, supplier_id: supplierId })
      .select(db.raw('SUM(total_amount) as totalVolume'));

    const totalVolume = Number(stats[0].totalVolume || 0);

    // 2. 评估回扣比例 (基于模拟规则)
    let rebateRatio = 0;
    let suggestion = 'MAINTAIN';
    let reason = 'Volume is not enough for rebate';

    if (totalVolume > 100000) {
      rebateRatio = 0.05; // 5% 回扣
      suggestion = 'CLAIM_REBATE';
      reason = `Volume exceeded $100k. Eligible for 5% rebate.`;
    } else if (totalVolume > 50000) {
      rebateRatio = 0.02; // 2% 回扣
      suggestion = 'CLAIM_REBATE';
      reason = `Volume exceeded $50k. Eligible for 2% rebate.`;
    }

    const rebateAmount = totalVolume * rebateRatio;

    const rebateRecord = {
      id: `REB-${tenantId}-${supplierId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      supplierId,
      totalVolume: Number(totalVolume),
      rebateRatio: Number(rebateRatio.toFixed(4)),
      rebateAmount: Number(rebateAmount.toFixed(2)),
      suggestion,
      reason,
      created_at: new Date()
    };

    // 3. 存储回扣记录
    await db(this.REBATE_TABLE)
      .insert(rebateRecord)
      .onConflict(['id'])
      .merge();

    return rebateRecord;
  }

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