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

/**
 * [BIZ_FIN_197] 供应商年度框架协议降本达成度审计 (Savings)
 * @description 考核采购团队，审计供应商框架协议降本达成度。
 */
export class SavingTrackerService {
  private static readonly SAVINGS_TABLE = 'cf_procurement_savings_audit';

  /**
   * 审计采购降本达成度
   */
  static async auditProcurementSavings(tenantId: string, supplierId: string) {
    logger.info(`[SavingTracker] Auditing savings for supplier: ${supplierId} for tenant: ${tenantId}`);

    // 1. 获取供应商框架协议约定的基准价和实际采购价
    const pos = await db('cf_purchase_orders')
      .where({ supplier_id: supplierId, tenant_id: tenantId })
      .select('id', 'total_amount', 'quantity', 'base_price'); // 假设基准价 base_price 在 PO 中

    const totalActualSpend = pos.reduce((acc, po) => acc + Number(po.total_amount), 0);
    const totalBaseSpend = pos.reduce((acc, po) => acc + (Number(po.base_price || 0) * Number(po.quantity || 0)), 0);

    const actualSavings = totalBaseSpend - totalActualSpend;
    const savingRatio = totalBaseSpend > 0 ? actualSavings / totalBaseSpend : 0;

    // 2. 考核达成度 (目标假设为 10% 降本)
    const targetSavingRatio = 0.1;
    const achievementRatio = savingRatio / targetSavingRatio;

    let performanceLevel = 'ON_TARGET';
    let performanceMsg = 'Procurement savings are on track';

    if (achievementRatio < 0.5) {
      performanceLevel = 'BELOW_TARGET';
      performanceMsg = `Savings ratio (${(savingRatio * 100).toFixed(2)}%) is significantly below target (10%). Need optimization.`;
    } else if (achievementRatio > 1.2) {
      performanceLevel = 'EXCEEDS_TARGET';
      performanceMsg = `Savings ratio (${(savingRatio * 100).toFixed(2)}%) exceeds target. Great performance.`;
    }

    const auditRecord = {
      id: `SA-${tenantId}-${supplierId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      supplierId,
      totalBaseSpend: Number(totalBaseSpend.toFixed(2)),
      totalActualSpend: Number(totalActualSpend.toFixed(2)),
      actualSavings: Number(actualSavings.toFixed(2)),
      savingRatio: Number(savingRatio.toFixed(4)),
      performanceLevel,
      performanceMsg,
      created_at: new Date()
    };

    // 3. 存储审计记录
    await db(this.SAVINGS_TABLE)
      .insert(auditRecord)
      .onConflict(['id'])
      .merge();

    return auditRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.SAVINGS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.SAVINGS_TABLE} table...`);
      await db.schema.createTable(this.SAVINGS_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('supplierId', 128).notNullable();
        table.decimal('totalBaseSpend', 15, 2);
        table.decimal('totalActualSpend', 15, 2);
        table.decimal('actualSavings', 15, 2);
        table.decimal('savingRatio', 5, 4);
        table.string('performanceLevel', 20); // E.g., BELOW_TARGET, ON_TARGET, EXCEEDS_TARGET
        table.text('performanceMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'supplierId']);
      });
    }
  }
}
