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

/**
 * [BIZ_OPS_152] 仓库温湿度敏感 SKU 损耗预警 (Storage)
 * @description 核心逻辑：监听 IoT 传感器传回的仓库温湿度数据，识别对环境敏感的 SKU（如电子元件、化妆品）是否存在变质或损坏风险。
 */
export class SensibleStockService {
  /**
   * 监控存储环境 (BIZ_OPS_152)
   */
  static async monitorStorageEnvironment(tenantId: string, warehouseId: string, sensorData: { temp: number; humidity: number }): Promise<any> {
    logger.info(`[SensibleStock] Monitoring storage environment for Warehouse: ${warehouseId}, Temp: ${sensorData.temp}°C, Humidity: ${sensorData.humidity}%`);

    try {
      // 1. 模拟识别敏感 SKU (如电子元件，要求湿度 < 40%)
      const thresholdTemp = 30; // 30°C
      const thresholdHumidity = 45; // 45%

      // 2. 环境超标识别
      if (sensorData.temp > thresholdTemp || sensorData.humidity > thresholdHumidity) {
        const advice = `STORAGE ENVIRONMENT ALERT: Warehouse ${warehouseId} environmental readings (Temp: ${sensorData.temp}°C, Humidity: ${sensorData.humidity}%) exceed thresholds. ` +
          `Potential loss of quality for sensitive electronic components or perishables. ` +
          `Suggesting immediate ventilation or climate control check.`;

        // 3. [UX_XAI_01] 记录决策证据链
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'WAREHOUSE_QUALITY_CONTROL',
          resourceId: warehouseId,
          decisionType: 'ENVIRONMENTAL_BREACH_WARNING',
          causalChain: advice,
          factors: [
            { name: 'TemperatureDeviation', value: sensorData.temp - thresholdTemp, weight: 0.5, impact: 'NEGATIVE' },
            { name: 'HumidityDeviation', value: sensorData.humidity - thresholdHumidity, weight: 0.5, impact: 'NEGATIVE' }
          ],
          traceId: 'storage-iot-' + Date.now()
        });

        return { success: true, breach: true, advice, status: 'PENDING_REVIEW' };
      }

      return { success: true, breach: false, message: 'Environment is stable' };
    } catch (err: any) {
      logger.error(`[SensibleStock][WARN] Monitoring failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
