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

export interface AgingRecord {
  skuId: string;
  warehouseId: string;
  agingDays: number;
  stockValue: number;
  suggestedAction: 'HOLD' | 'DISCOUNT' | 'CLEARANCE' | 'LIQUIDATE';
}

/**
 * [BIZ_OPS_156] 海外仓库龄过长导致的清仓建议 (Aging Inventory)
 * @description 核心逻辑：分析 cf_inventory 中的入库时间 (arrival_at) 与最后动销时间 (last_sold_at)，识别死货并生成清仓策略。
 */
export class InventoryAgingService {
  private static readonly AGING_THRESHOLD_DAYS = 90; // 90天为死货门槛

  /**
   * 执行库龄分析
   */
  static async analyzeAging(tenantId: string): Promise<AgingRecord[]> {
    logger.info(`[InventoryAging] Analyzing inventory aging for tenant: ${tenantId}`);

    try {
      const threshold = InventoryAgingService.AGING_THRESHOLD_DAYS;
      // 1. 获取库龄超过 90 天或入库后未销售的 SKU (Zero-Mock Policy)
      const agingStocks = await db('cf_inventory as i')
        .join('cf_product as p', 'i.sku_id', 'p.id')
        .where('i.tenant_id', tenantId)
        .where('i.quantity_on_hand', '>', 0)
        .where(function() {
          this.where(db.raw("TIMESTAMPDIFF(DAY, i.arrival_at, NOW()) > ?", [threshold]))
            .orWhere(db.raw("TIMESTAMPDIFF(DAY, i.last_sold_at, NOW()) > ?", [threshold]));
        })
        .select(
          'i.sku_id',
          'i.warehouse_id',
          'i.arrival_at',
          'i.last_sold_at',
          'i.quantity_on_hand',
          'p.purchase_price'
        );

      const results: AgingRecord[] = [];

      for (const stock of agingStocks) {
        const lastActivity = stock.last_sold_at || stock.arrival_at;
        const agingDays = Math.floor((Date.now() - new Date(lastActivity).getTime()) / (1000 * 3600 * 24));
        const stockValue = Number(stock.quantity_on_hand) * Number(stock.purchase_price || 0);

        let suggestedAction: AgingRecord['suggestedAction'] = 'HOLD';
        let discountRate = 0;

        // 2. 动态清仓策略
        if (agingDays > 180) {
          suggestedAction = 'LIQUIDATE';
          discountRate = 0.7; // 3折清仓
        } else if (agingDays > 120) {
          suggestedAction = 'CLEARANCE';
          discountRate = 0.5; // 5折清仓
        } else if (agingDays > 90) {
          suggestedAction = 'DISCOUNT';
          discountRate = 0.2; // 8折促销
        }

        if (suggestedAction !== 'HOLD') {
          const reason = `SKU ${stock.sku_id} has been idle for ${agingDays} days in ${stock.warehouse_id}. ` +
            `Estimated asset tie-up: $${stockValue.toFixed(2)}. Suggested action: ${suggestedAction} (${(discountRate * 100).toFixed(0)}% OFF).`;

          // 3. [UX_XAI_01] 记录决策证据链
          await DecisionExplainabilityEngine.logDecision({
            tenantId,
            module: 'INVENTORY_AGING',
            resourceId: `${stock.sku_id}:${stock.warehouse_id}`,
            decisionType: 'INVENTORY_LIQUIDATION_SUGGESTION',
            causalChain: reason,
            factors: [
              { name: 'AgingDays', value: agingDays, weight: 0.7, impact: 'NEGATIVE' },
              { name: 'StockValue', value: stockValue, weight: 0.3, impact: 'NEGATIVE' }
            ],
            traceId: `aging-audit-${Date.now()}`
          });
        }

        results.push({
          skuId: stock.sku_id,
          warehouseId: stock.warehouse_id,
          agingDays,
          stockValue,
          suggestedAction
        });
      }

      return results;
    } catch (err: any) {
      logger.error(`[InventoryAging][FATAL] Analysis failed: ${err.message}`);
      throw {
        category: 'Logic Conflict',
        rootCause: 'Failed to calculate inventory aging due to missing date fields',
        mitigation: 'Ensure cf_inventory arrival_at and last_sold_at are populated'
      };
    }
  }
}
