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

export interface SupplierCapacity {
  supplierId: string;
  maxDailyCapacity: number;
  currentBacklog: number;
  avgLeadTimeDays: number;
  trend: 'UP' | 'DOWN' | 'STABLE';
}

/**
 * [BIZ_TRADE_30] 自动化供应商产能预警 (Supplier Capacity Watch)
 * @description 监控供应商订单积压，预测交期风险并建议备选源。
 */
export class SupplierCapacityWatchService {
  private static readonly CAPACITY_TABLE = 'cf_supplier_capacities';
  private static readonly ALERT_TABLE = 'cf_supplier_capacity_alerts';

  /**
   * 执行供应商产能审计
   */
  static async auditSupplierCapacity(tenantId: string, supplierId: string) {
    logger.info(`[CapacityWatch] Auditing supplier capacity for: ${supplierId}`);

    // 1. 获取供应商基础产能数据
    const capacity = await db(this.CAPACITY_TABLE).where({ supplierId }).first();
    if (!capacity) {
      logger.warn(`[CapacityWatch] No capacity data found for supplier: ${supplierId}`);
      return null;
    }

    // 2. 计算积压比例与风险
    const backlogRatio = capacity.currentBacklog / capacity.maxDailyCapacity;
    const estimatedDelayDays = Math.ceil(capacity.currentBacklog / capacity.maxDailyCapacity);
    const riskScore = Math.min(100, (backlogRatio * 20) + (capacity.avgLeadTimeDays * 5));

    let severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' = 'LOW';
    if (riskScore > 80) severity = 'CRITICAL';
    else if (riskScore > 50) severity = 'HIGH';
    else if (riskScore > 30) severity = 'MEDIUM';

    // 3. 生成并记录风险预警
    const alertId = `CAPA-${supplierId}-${Date.now()}`;
    const alert = {
      id: alertId,
      tenant_id: tenantId,
      supplier_id: supplierId,
      backlog_ratio: Number(backlogRatio.toFixed(2)),
      estimated_delay_days: estimatedDelayDays,
      risk_score: riskScore,
      severity,
      description: `供应商产能积压比例达 ${Math.round(backlogRatio * 100)}%，预估交期延误 ${estimatedDelayDays} 天。`,
      created_at: new Date()
    };

    await db(this.ALERT_TABLE).insert(alert);

    if (severity === 'CRITICAL' || severity === 'HIGH') {
      logger.error(`[CapacityWatch] ${severity} RISK detected for supplier ${supplierId}! Generating failover advice...`);
      // 触发备选源建议
    }

    return alert;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasCapacityTable = await db.schema.hasTable(this.CAPACITY_TABLE);
    if (!hasCapacityTable) {
      logger.info(`📦 Creating ${this.CAPACITY_TABLE} table...`);
      await db.schema.createTable(this.CAPACITY_TABLE, (table) => {
        table.string('supplierId', 64).primary();
        table.integer('maxDailyCapacity').notNullable();
        table.integer('currentBacklog').defaultTo(0);
        table.integer('avgLeadTimeDays').defaultTo(7);
        table.string('trend', 16).defaultTo('STABLE');
        table.timestamp('updated_at').defaultTo(db.fn.now());
      });
    }

    const hasAlertTable = await db.schema.hasTable(this.ALERT_TABLE);
    if (!hasAlertTable) {
      logger.info(`📦 Creating ${this.ALERT_TABLE} table...`);
      await db.schema.createTable(this.ALERT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('supplier_id', 64).notNullable();
        table.decimal('backlog_ratio', 10, 2);
        table.integer('estimated_delay_days');
        table.integer('risk_score');
        table.string('severity', 16);
        table.text('description');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'supplier_id']);
        table.index(['severity']);
      });
    }
  }
}
