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

/**
 * [BIZ_FIN_190] 供应商资金池/信用额度自动预警 (Credit Limit)
 * @description 监控供应商信用额度，防止采购中断。
 */
export class CreditMonitorService {
  private static readonly MONITOR_TABLE = 'cf_vendor_credit_monitors';

  /**
   * 监控供应商信用额度
   */
  static async monitorVendorCredit(tenantId: string, vendorId: string) {
    logger.info(`[CreditMonitor] Monitoring vendor credit: ${vendorId} for tenant: ${tenantId}`);

    // 1. 获取供应商信用额度和当前已用额度 (未结算 PO)
    const vendor = await db('cf_suppliers').where({ id: vendorId, tenant_id: tenantId }).first();
    if (!vendor) return null;

    const stats = await db('cf_purchase_orders')
      .where({ supplier_id: vendorId, tenant_id: tenantId, status: 'PENDING_PAYMENT' })
      .select(db.raw('SUM(total_amount) as usedCredit'));

    const creditLimit = Number(vendor.credit_limit || 10000); // 默认 10k 额度
    const usedCredit = Number(stats[0].usedCredit || 0);
    const availableCredit = creditLimit - usedCredit;

    // 2. 预警级别
    let riskLevel = 'LOW';
    let alertMsg = 'Credit limit is sufficient';

    const usageRatio = creditLimit > 0 ? usedCredit / creditLimit : 0;

    if (usageRatio > 0.9) {
      riskLevel = 'CRITICAL';
      alertMsg = `Credit limit usage exceeded 90% (${(usageRatio * 100).toFixed(2)}%). Procurement may be blocked.`;
    } else if (usageRatio > 0.7) {
      riskLevel = 'WARNING';
      alertMsg = `Credit limit usage exceeded 70% (${(usageRatio * 100).toFixed(2)}%). Monitor closely.`;
    }

    const monitorLog = {
      id: `CM-${tenantId}-${vendorId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      vendorId,
      creditLimit,
      usedCredit,
      availableCredit,
      usageRatio: Number(usageRatio.toFixed(4)),
      riskLevel,
      alertMsg,
      created_at: new Date()
    };

    // 3. 存储监控记录
    await db(this.MONITOR_TABLE)
      .insert(monitorLog)
      .onConflict(['id'])
      .merge();

    return monitorLog;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MONITOR_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MONITOR_TABLE} table...`);
      await db.schema.createTable(this.MONITOR_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('vendorId', 128).notNullable();
        table.decimal('creditLimit', 15, 2);
        table.decimal('usedCredit', 15, 2);
        table.decimal('availableCredit', 15, 2);
        table.decimal('usageRatio', 5, 4);
        table.string('riskLevel', 20); // E.g., LOW, WARNING, CRITICAL
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'vendorId']);
      });
    }
  }
}
