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

/**
 * [BIZ_OPS_151] 采购单价格波动与预算偏差预警 (Budget)
 * @description 核心逻辑：自动对比 SKU 的历史平均采购价与当前采购单价，当波动超过 10% 或 偏离年度预算时，触发预警。
 */
export class ProcurementAuditService {
  /**
   * 审计采购价格波动 (BIZ_OPS_151)
   */
  static async auditProcurementPrices(tenantId: string, productId: string, currentPrice: number): Promise<any> {
    logger.info(`[ProcurementAudit] Auditing price for Product: ${productId}, Price: ${currentPrice}`);

    try {
      // 1. 获取历史平均采购价
      const product = await db('cf_product').where({ id: productId }).first();
      const historicalPrice = product.purchase_price || currentPrice;

      // 2. 波动分析
      const drift = (currentPrice - historicalPrice) / historicalPrice;

      if (Math.abs(drift) > 0.10) {
        const advice = `PRICE FLUCTUATION ALERT: Current price (${currentPrice}) is ${(drift * 100).toFixed(1)}% ` +
          `${drift > 0 ? 'higher' : 'lower'} than historical average (${historicalPrice}). ` +
          `Suggesting review of supplier terms or batch size.`;

        // 3. [UX_XAI_01] 记录决策证据链
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'PROCUREMENT_GOVERNANCE',
          resourceId: productId,
          decisionType: 'PRICE_DRIFT_WARNING',
          causalChain: advice,
          factors: [
            { name: 'DriftPercentage', value: (drift * 100).toFixed(1) + '%', weight: 0.8, impact: drift > 0 ? 'NEGATIVE' : 'POSITIVE' },
            { name: 'HistoricalPrice', value: historicalPrice, weight: 0.2, impact: 'NEUTRAL' }
          ],
          traceId: 'procure-audit-' + Date.now()
        });

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

      return { success: true, drift, message: 'Price is stable' };
    } catch (err: any) {
      logger.error(`[ProcurementAudit][WARN] Audit failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
