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

export interface MarketingEvent {
  id?: number;
  tenantId: string;
  name: string;
  type: 'PROMOTION' | 'RECOVERY' | 'SEASONAL';
  startTime: Date;
  endTime: Date;
  status: 'ACTIVE' | 'PAUSED' | 'COMPLETED';
  config: any;
}

/**
 * [BIZ_AUTO_03] 营销日历自动化服务
 * @description 管理营销事件并根据日历自动触发营销动作
 */
export class MarketingCalendarService {
  private static readonly TABLE_NAME = 'cf_marketing_calendar';

  /**
   * 注册营销事件
   */
  static async registerEvent(event: MarketingEvent): Promise<number> {
    logger.info(`[MarketingCalendar] Registering ${event.type} event: ${event.name}`);
    
    const [id] = await db(this.TABLE_NAME).insert({
      tenant_id: event.tenantId,
      name: event.name,
      type: event.type,
      start_time: event.startTime,
      end_time: event.endTime,
      status: event.status,
      config: JSON.stringify(event.config),
      created_at: new Date(),
      updated_at: new Date()
    });
    
    return id;
  }

  /**
   * 周期性检查并执行到期的营销事件 (由定时任务调用)
   */
  static async executeDueEvents(): Promise<void> {
    const now = new Date();
    const dueEvents = await db(this.TABLE_NAME)
      .where('status', 'ACTIVE')
      .andWhere('start_time', '<=', now)
      .andWhere('end_time', '>=', now);

    for (const event of dueEvents) {
      await this.triggerMarketingAction(event);
    }
  }

  /**
   * 根据事件类型触发具体的营销动作
   */
  private static async triggerMarketingAction(event: any): Promise<void> {
    const config = typeof event.config === 'string' ? JSON.parse(event.config) : event.config;
    
    logger.info(`[MarketingCalendar] Triggering action for event: ${event.name} (${event.type})`);

    switch (event.type) {
      case 'RECOVERY':
        // 触发弃购挽留逻辑 (BIZ_EXT_12)
        // 假设 config 包含挽留规则
        await MarketingService.sendRecoveryEmail({
          tenantId: event.tenant_id,
          templateId: config.templateId || 'DEFAULT_RECOVERY',
          delayHours: config.delayHours || 24
        } as any);
        break;

      case 'PROMOTION':
        // 触发促销活动，如自动应用全店折扣
        logger.info(`[MarketingCalendar] [API_CALL] Applying store-wide discount: ${config.discount}%`);
        break;

      case 'SEASONAL':
        // 触发季节性活动，如自动更换独立站 Banner
        logger.info(`[MarketingCalendar] [API_CALL] Updating store banners for ${event.name}`);
        break;
    }
  }
}
