import db from '../config/database';
import { AuditService } from './AuditService';
import { SupplierService } from './SupplierService';

/**
 * [BIZ_AUTO_13] 供应商生产进度实时感知与预警
 * 负责监控 PO（采购订单）的生产进度，并根据异常（如进度停滞）自动触发预警
 */
export class FactoryMonitorService {
  /**
   * 记录并分析生产进度
   */
  static async monitorProduction(
    tenantId: string,
    supplierId: string,
    purchaseOrderId: string,
    completionPercentage: number,
    observationData: string,
    traceId: string
  ): Promise<void> {
    // 1. 获取 PO 信息
    const po = await db('cf_purchase_orders').where({ id: purchaseOrderId }).first();
    if (!po) return;

    // 2. 风险判定逻辑 (如果完成度低于预期，例如 PO 创建 7 天后仍为 0%)
    let riskStatus: 'NORMAL' | 'DELAY_RISK' | 'CRITICAL_DELAY' = 'NORMAL';
    const daysSinceCreated = Math.floor((Date.now() - new Date(po.created_at).getTime()) / (1000 * 60 * 60 * 24));
    
    if (daysSinceCreated > 10 && completionPercentage < 20) riskStatus = 'CRITICAL_DELAY';
    else if (daysSinceCreated > 5 && completionPercentage < 10) riskStatus = 'DELAY_RISK';

    // 3. 持久化监控记录
    const [id] = await db('cf_factory_monitor').insert({
      tenant_id: tenantId,
      supplier_id: supplierId,
      purchase_order_id: purchaseOrderId,
      completion_percentage: completionPercentage,
      risk_status: riskStatus,
      observation_data: observationData
    });

    // 4. 触发高风险预警 (BIZ_SC_14 Risk Radar 联动)
    if (riskStatus !== 'NORMAL') {
      await db('cf_risk_radar').insert({
        tenant_id: tenantId,
        product_id: po.product_id,
        type: 'DELAY',
        severity: riskStatus === 'CRITICAL_DELAY' ? 'HIGH' : 'MEDIUM',
        message: `Supplier ${supplierId} reported low production progress: ${completionPercentage}%`,
        status: 'ACTIVE'
      });

      // 审计记录
      await AuditService.log({
        tenant_id: tenantId,
        action: 'FACTORY_DELAY_ALERT',
        target_type: 'FACTORY_MONITOR',
        target_id: id.toString(),
        trace_id: traceId,
        new_data: JSON.stringify({ riskStatus, completionPercentage }),
        metadata: JSON.stringify({ purchaseOrderId, supplierId })
      });
    }
  }

  /**
   * 获取租户所有高风险生产监控任务
   */
  static async getHighRiskProductions(tenantId: string) {
    return await db('cf_factory_monitor')
      .where({ tenant_id: tenantId })
      .whereIn('risk_status', ['DELAY_RISK', 'CRITICAL_DELAY'])
      .orderBy('created_at', 'desc');
  }
}
