import db from '../config/database';
import { logger } from '../utils/logger';
import { MarketingCalendarService } from './MarketingCalendarService';

export interface LiquidationAdvice {
  tenantId: string;
  productId: string;
  stockAgeDays: number;
  quantity: number;
  suggestedDiscount: number;
}

/**
 * [BIZ_AUTO_07] 呆滞库存 AI 清理服务
 * @description 识别库龄过长的 SKU，自动生成打折清仓建议并联动营销日历
 */
export class SlowMovingStockService {
  /**
   * 分析并生成呆滞库存清理建议 (BIZ_AUTO_07)
   */
  static async analyzeSlowMovingStock(tenantId: string): Promise<LiquidationAdvice[]> {
    logger.info(`[SlowMoving] Analyzing stock age for Tenant: ${tenantId}`);

    // 1. 查找库龄超过 90 天且最近 30 天销量 < 5 的商品
    const ninetyDaysAgo = new Date();
    ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);

    const slowMovingItems = await db('cf_inventory')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '<', ninetyDaysAgo)
      .andWhere('available_stock', '>', 0);

    const advices: LiquidationAdvice[] = [];

    for (const item of slowMovingItems) {
      // 检查最近销量
      const recentSales = await db('cf_orders')
        .where({ product_id: item.product_id, tenant_id: tenantId })
        .andWhere('created_at', '>', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
        .count('id as count')
        .first();

      if (Number(recentSales?.count || 0) < 5) {
        const stockAge = Math.floor((Date.now() - new Date(item.created_at).getTime()) / (24 * 60 * 60 * 1000));
        
        advices.push({
          tenantId,
          productId: item.product_id,
          stockAgeDays: stockAge,
          quantity: item.available_stock,
          suggestedDiscount: stockAge > 180 ? 0.5 : 0.3 // 超过半年 5 折，否则 7 折
        });
      }
    }

    return advices;
  }

  /**
   * 自动创建清仓活动 (BIZ_AUTO_07)
   */
  static async triggerLiquidationCampaign(advice: LiquidationAdvice): Promise<void> {
    logger.info(`[SlowMoving] Triggering liquidation campaign for Product: ${advice.productId}`);

    await MarketingCalendarService.registerEvent({
      tenantId: advice.tenantId,
      name: `Clearance: Product ${advice.productId}`,
      type: 'PROMOTION',
      startTime: new Date(),
      endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 持续一周
      status: 'ACTIVE',
      config: {
        productId: advice.productId,
        discount: advice.suggestedDiscount * 100,
        channel: 'STORE_WIDE'
      }
    });
  }
}
