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

/**
 * [BIZ_INV_30] 滞销库存深度治理建议 (Aging Inventory)
 * @description 联动 InventoryAgingService 进行库龄分析，并自动生成针对滞销 SKU 的阶梯折扣建议。
 */
export class AgingInventoryService {
  private static readonly TABLE_NAME = 'cf_aging_inventory_advice';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.TABLE_NAME);
    if (!exists) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('sku_id', 64).notNullable();
        table.string('warehouse_id', 64).notNullable();
        table.integer('aging_days');
        table.decimal('stock_value', 10, 2);
        table.string('suggested_action', 32);
        table.float('suggested_discount');
        table.string('status', 32).defaultTo('SUGGESTED');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        table.index(['tenant_id', 'status']);
        table.index('sku_id');
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * [BIZ_INV_30] 生成滞销治理建议 (Generate Aging Advice)
   */
  static async generateAgingAdvice(tenantId: string, shopId: string): Promise<number> {
    logger.info(`[AgingInventory] Generating advice for Tenant: ${tenantId}, Shop: ${shopId}`);
    const traceId = `aging-advice-${Date.now()}`;

    // 1. 联动 InventoryAgingService 获取库龄分析结果
    const agingRecords = await InventoryAgingService.analyzeAging(tenantId);
    
    let adviceCount = 0;

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

      // 2. 计算建议折扣率
      let suggestedDiscount = 0;
      if (record.suggestedAction === 'LIQUIDATE') suggestedDiscount = 0.7;
      else if (record.suggestedAction === 'CLEARANCE') suggestedDiscount = 0.5;
      else if (record.suggestedAction === 'DISCOUNT') suggestedDiscount = 0.2;

      // 3. 持久化至本地业务表
      await db(this.TABLE_NAME).insert({
        tenant_id: tenantId,
        sku_id: record.skuId,
        warehouse_id: record.warehouseId,
        aging_days: record.agingDays,
        stock_value: record.stockValue,
        suggested_action: record.suggestedAction,
        suggested_discount: suggestedDiscount,
        status: 'SUGGESTED',
        trace_id: traceId,
        created_at: new Date(),
        updated_at: new Date()
      });

      // 4. 联动 AdviceService 录入全局建议包 (Actionable Insight)
      const insight: ActionableInsight = {
        type: 'INVENTORY',
        title: `Aging Inventory Alert: ${record.skuId}`,
        description: `SKU has been idle for ${record.agingDays} days. Potential dead stock value: $${record.stockValue.toFixed(2)}.`,
        impact: record.stockValue > 1000 ? 'high' : 'medium',
        confidence: 0.95,
        suggestedAction: `Apply ${record.suggestedAction} with ${(suggestedDiscount * 100).toFixed(0)}% discount.`,
        metadata: {
          productId: record.skuId,
          warehouseId: record.warehouseId,
          agingDays: record.agingDays,
          discount: suggestedDiscount,
          action: record.suggestedAction
        }
      };

      await AdviceService.recordAdvice({
        tenantId,
        shopId,
        insight,
        traceId
      });

      adviceCount++;
    }

    logger.info(`[AgingInventory] Generated ${adviceCount} aging insights for Tenant: ${tenantId}`);
    return adviceCount;
  }
}
