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

/**
 * [BIZ_OPS_142] 海外仓入库异常自动拍照取证建议 (Warehouse)
 * @description 核心逻辑：监听海外仓入库异常事件（如破损、少件），自动向仓库操作员下发“拍照取证”指令，并将证据关联至纠纷单。
 */
export class WMSAdvisor {
  private static readonly WMS_AUDIT_TABLE = 'cf_wms_anomaly_audit';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.WMS_AUDIT_TABLE);
    if (!hasTable) {
      await db.schema.createTable(this.WMS_AUDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('warehouse_id', 64);
        table.string('batch_id', 64);
        table.string('anomaly_type', 64);
        table.text('instruction');
        table.string('status', 32).defaultTo('PENDING_REVIEW');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 处理入库异常并下发取证建议 (BIZ_OPS_142)
   */
  static async suggestEvidenceCollection(tenantId: string, anomaly: { warehouseId: string; batchId: string; type: 'DAMAGED' | 'SHORTAGE' }): Promise<any> {
    logger.info(`[WMSAdvisor] Processing anomaly: ${anomaly.type} for batch: ${anomaly.batchId}`);

    try {
      const instruction = `URGENT: ${anomaly.type} detected in Batch ${anomaly.batchId}. ` +
        `Please take high-resolution photos of the outer box and items before processing.`;

      // 1. 记录取证任务建议
      const [suggestionId] = await db(this.WMS_AUDIT_TABLE).insert({
        tenant_id: tenantId,
        warehouse_id: anomaly.warehouseId,
        batch_id: anomaly.batchId,
        anomaly_type: anomaly.type,
        instruction: instruction,
        status: 'PENDING_REVIEW',
        created_at: new Date()
      });

      // 2. [UX_XAI_01] 记录决策证据链
      await DecisionExplainabilityEngine.logDecision({
        tenantId,
        module: 'WAREHOUSE_OPERATIONS',
        resourceId: String(suggestionId),
        decisionType: 'EVIDENCE_COLLECTION_INSTRUCTION',
        causalChain: instruction,
        factors: [
          { name: 'AnomalyType', value: anomaly.type, weight: 0.8, impact: 'NEGATIVE' },
          { name: 'BatchValue', value: 'MOCK_VALUE', weight: 0.2, impact: 'NEUTRAL' }
        ],
        traceId: 'wms-advisor-' + Date.now()
      });

      return { success: true, suggestionId, instruction, status: 'PENDING_REVIEW' };
    } catch (err: any) {
      logger.error(`[WMSAdvisor][WARN] Suggestion failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
