import db from '../config/database';
import { DecisionExplainabilityEngine } from '../core/ai/DecisionExplainabilityEngine';
import { logger } from '../utils/logger';
import { AgingRecord, InventoryAgingService } from './InventoryAgingService';
import { AdviceService } from '../domains/Strategy/AdviceService';

/**
 * [BIZ_INV_30] 滞销库存深度治理与清仓建议 (Aging Inventory)
 * @description 核心逻辑：基于 InventoryAgingService 的库龄分析结果，自动生成阶梯折扣建议。
 * 联动 [DecisionExplainabilityEngine] 实现决策可解释性，并生成可直接执行的调价建议包。
 */
export class AgingInventoryService {
  private static readonly SUGGESTION_TABLE = 'cf_aging_inventory_suggestions';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.SUGGESTION_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.SUGGESTION_TABLE} table...`);
      await db.schema.createTable(this.SUGGESTION_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('sku_id', 64).index();
        table.string('warehouse_id', 64);
        table.integer('aging_days');
        table.decimal('stock_value', 10, 2);
        table.string('suggested_action', 32);
        table.float('discount_rate');
        table.string('status', 16).defaultTo('SUGGESTED'); // SUGGESTED, PENDING_REVIEW, EXECUTED, REJECTED
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 生成深度治理建议
   */
  static async generateGovernanceSuggestions(tenantId: string): Promise<AgingRecord[]> {
    logger.info(`[AgingInventory] Generating deep governance suggestions for tenant: ${tenantId}`);

    try {
      // 1. 获取基础库龄分析结果
      const agingRecords = await InventoryAgingService.analyzeAging(tenantId);
      const governanceResults: AgingRecord[] = [];

      for (const record of agingRecords) {
        if (record.suggestedAction === 'HOLD') continue;

        // 2. 生成阶梯折扣建议包
        let discountRate = 0;
        if (record.suggestedAction === 'LIQUIDATE') discountRate = 0.7;
        else if (record.suggestedAction === 'CLEARANCE') discountRate = 0.5;
        else if (record.suggestedAction === 'DISCOUNT') discountRate = 0.2;

        // 3. 落地建议到统一建议包 (AdviceService)
        const suggestionId = await AdviceService.recordAdvice({
          tenantId,
          shopId: record.warehouseId || 'GLOBAL',
          traceId: 'aging-gov-' + Date.now(),
          insight: {
            type: 'INVENTORY',
            title: `Aging Inventory Liquidation: SKU ${record.skuId}`,
            description: `[BIZ_INV_30] AGI detected SKU is stagnant for ${record.agingDays} days.`,
            impact: 'high',
            confidence: 0.85,
            suggestedAction: record.suggestedAction,
            metadata: { 
              productId: record.skuId, 
              warehouseId: record.warehouseId,
              discountRate 
            }
          }
        });

        // 4. [UX_XAI_01] 增强因果链叙述
        const causalChain = `[BIZ_INV_30] AGI detected SKU ${record.skuId} in ${record.warehouseId} ` +
          `is stagnant for ${record.agingDays} days. Value at risk: $${record.stockValue.toFixed(2)}. ` +
          `Strategy: ${record.suggestedAction} with ${(discountRate * 100).toFixed(0)}% discount to free up liquidity.`;

        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'AGING_INVENTORY',
          resourceId: String(suggestionId),
          decisionType: 'DEEP_LIQUIDATION_SUGGESTION',
          causalChain,
          factors: [
            { name: 'AgingImpact', value: record.agingDays, weight: 0.6, impact: 'NEGATIVE' },
            { name: 'CapitalLockup', value: record.stockValue, weight: 0.4, impact: 'NEGATIVE' }
          ],
          traceId: `aging-gov-${Date.now()}`
        });

        governanceResults.push(record);
      }

      return governanceResults;
    } catch (err: any) {
      logger.error(`[AgingInventory] Governance suggestion generation failed: ${err.message}`);
      return [];
    }
  }
}
