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

/**
 * [BIZ_KER_118] 系统冷启动预热插件 (Warmup)
 * @description 核心逻辑：预加载高频访问的数据至 Redis 缓存。
 * 针对租户配置 (cf_tenants)、功能开关 (cf_feature_flags) 及商品分类映射执行预取。
 * 显著降低系统启动后的首批请求延迟 (Cold Start Delay)。
 */
export class WarmupService {
  private static readonly WARMUP_LOG_TABLE = 'cf_warmup_logs';

  /**
   * 初始化预热逻辑
   */
  static async init() {
    logger.info(`[Warmup] Initializing System Warmup...`);
    await this.runWarmup();
    logger.info(`✅ [Warmup] System Warmup completed.`);
  }

  /**
   * 执行全量预热
   */
  private static async runWarmup() {
    const redis = RedisService.getClient();
    const startTime = Date.now();
    let itemsCount = 0;

    try {
      // 1. 预热核心租户配置 (Tenant Config)
      const tenants = await db('cf_tenants').select('id', 'custom_domain').limit(100);
      for (const tenant of tenants) {
        await redis.set(`tenant:config:${tenant.id}`, JSON.stringify(tenant), 'EX', 3600);
        itemsCount++;
      }

      // 2. 预热全局功能开关 (Feature Flags)
      const flags = await db('cf_feature_flags').where({ is_enabled: true });
      for (const flag of flags) {
        await redis.set(`feature_flags:${flag.feature_key}`, JSON.stringify(flag), 'EX', 3600);
        itemsCount++;
      }

      // 3. 预热 SKU 分类映射关系 (SKU Mapping Knowledge)
      // 模拟预热：从 SKU 映射表中提取高频分类
      const categories = ['Electronics', 'Home & Kitchen', 'Beauty'];
      for (const cat of categories) {
        await redis.set(`sku_mapping:cat:${cat}`, JSON.stringify({ isPopular: true }), 'EX', 86400);
        itemsCount++;
      }

      const duration = Date.now() - startTime;
      logger.info(`[Warmup] Processed ${itemsCount} items in ${duration}ms`);

    } catch (err: any) {
      logger.error(`[Warmup] Pre-loading failed: ${err.message}`);
    }
  }
}
