import db from '../config/database';
import { logger } from '../utils/logger';
import { InventoryService } from './InventoryService';
import { AdviceService } from '../domains/Strategy/AdviceService';

export interface RiskEvent {
  tenantId: string;
  productId: string;
  type: 'STOCKOUT' | 'DELAY' | 'QUALITY';
  severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  message: string;
  metadata?: any;
}

/**
 * [BIZ_TRADE_03] 供应链风险预警服务 (Supply Chain Risk Radar)
 * @description 预测性识别库存缺口、物流延迟与质量风险
 */
export class RiskRadarService {
  private static readonly RISK_TABLE = 'cf_risk_radar';

  /**
   * 注册风险事件并触发预警 (BIZ_TRADE_03)
   */
  static async recordRisk(event: RiskEvent, traceId: string): Promise<void> {
    logger.info(`[RiskRadar] Recording ${event.severity} risk: ${event.type} for Product: ${event.productId}`);

    // 1. 持久化风险记录
    const [riskId] = await db(this.RISK_TABLE).insert({
      tenant_id: event.tenantId,
      product_id: event.productId,
      type: event.type,
      severity: event.severity,
      message: event.message,
      metadata: JSON.stringify(event.metadata || {}),
      status: 'ACTIVE',
      created_at: new Date(),
      updated_at: new Date()
    });

    // 2. 如果风险等级较高，自动生成 Advice 建议 (BIZ_AI_16-EXT)
    if (event.severity === 'HIGH' || event.severity === 'CRITICAL') {
      await this.triggerRiskAdvice(event, traceId);
    }
  }

  /**
   * 自动生成风险应对建议 (BIZ_TRADE_03)
   */
  private static async triggerRiskAdvice(event: RiskEvent, traceId: string): Promise<void> {
    let suggestedAction = '';
    let adviceType: 'PRICING' | 'INVENTORY' | 'ARBITRAGE' = 'INVENTORY';

    if (event.type === 'STOCKOUT') {
      suggestedAction = 'Restock immediately from alternative supplier.';
      adviceType = 'INVENTORY';
    } else if (event.type === 'DELAY') {
      suggestedAction = 'Pause ads to slow down sales and prevent backorders.';
      adviceType = 'MARKETING' as any; // Marketing logic for budget control
    }

    await AdviceService.recordAdvice({
      tenantId: event.tenantId,
      shopId: event.metadata?.shopId || 'DEFAULT',
      traceId,
      insight: {
        type: adviceType,
        title: `Risk Warning: ${event.type}`,
        description: event.message,
        impact: 'high',
        confidence: 0.95,
        suggestedAction,
        metadata: { productId: event.productId, riskType: event.type, severity: event.severity }
      }
    });
  }

  /**
   * 周期性库存风险扫描 (BIZ_TRADE_03)
   */
  static async performRiskScan(tenantId: string): Promise<void> {
    logger.info(`[RiskRadar] Performing risk scan for Tenant: ${tenantId}`);

    // 1. 扫描即将缺货的商品 (基于 InventoryService 预测)
    // 假设 InventoryService.predictSKUDemand 返回预测销量
    const inventory = await db('cf_inventory').where({ tenant_id: tenantId });

    for (const stock of inventory) {
      const velocity = await this.getSalesVelocity(stock.product_id, tenantId);
      const daysLeft = velocity > 0 ? stock.available_stock / velocity : 999;

      if (daysLeft < 3) {
        await this.recordRisk({
          tenantId,
          productId: stock.product_id,
          type: 'STOCKOUT',
          severity: 'CRITICAL',
          message: `Stock will run out in ${daysLeft.toFixed(1)} days based on current velocity.`
        }, `SCAN-${Date.now()}`);
      } else if (daysLeft < 7) {
        await this.recordRisk({
          tenantId,
          productId: stock.product_id,
          type: 'STOCKOUT',
          severity: 'MEDIUM',
          message: `Stock is running low. Expected to run out in ${daysLeft.toFixed(1)} days.`
        }, `SCAN-${Date.now()}`);
      }
    }
  }

  private static async getSalesVelocity(productId: string, tenantId: string): Promise<number> {
    // 模拟销量速度计算 (最近 7 天平均日销量)
    return Math.random() * 5; 
  }
}
