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

/**
 * [BIZ_MKT_12] AI 驱动的全球节日营销日历自动执行
 * 负责自动扫描全球节日（如黑五、斋月等），并基于租户配置自动调度营销活动
 */
export class FestivalMarketingService {
  /**
   * 自动调度节日营销
   */
  static async scheduleFestivalCampaigns(tenantId: string, region: string, traceId: string): Promise<void> {
    // 1. 获取该地区即将到来的节日 (模拟获取全球节日日历数据)
    const festivals = [
      { name: 'Black Friday', startDate: '2026-11-27', endDate: '2026-11-30' },
      { name: 'Cyber Monday', startDate: '2026-12-01', endDate: '2026-12-01' }
    ];

    for (const festival of festivals) {
      // 检查是否已调度
      const existing = await db('cf_festival_marketing')
        .where({ tenant_id: tenantId, festival_name: festival.name, region })
        .first();

      if (!existing) {
        await db.transaction(async (trx) => {
          const [id] = await trx('cf_festival_marketing').insert({
            tenant_id: tenantId,
            festival_name: festival.name,
            region,
            start_date: new Date(festival.startDate),
            end_date: new Date(festival.endDate),
            campaign_config: JSON.stringify({ autoDiscount: 0.2, adBudget: 500 }),
            status: 'SCHEDULED'
          });

          // 联动 MarketingCalendarService 发起活动
          await MarketingCalendarService.createEvent(tenantId, {
            name: `${festival.name} Promotion`,
            type: 'SEASONAL',
            start_time: new Date(festival.startDate),
            end_time: new Date(festival.endDate),
            config: { festivalId: id }
          });

          // 审计记录
          await AuditService.log({
            tenant_id: tenantId,
            action: 'FESTIVAL_MARKETING_SCHEDULED',
            target_type: 'MARKETING_CAMPAIGN',
            target_id: id.toString(),
            trace_id: traceId,
            new_data: JSON.stringify({ festivalName: festival.name, region }),
            metadata: JSON.stringify({ startDate: festival.startDate })
          });
        });
      }
    }
  }

  /**
   * 获取租户所有节日营销计划
   */
  static async getScheduledFestivals(tenantId: string) {
    return await db('cf_festival_marketing')
      .where({ tenant_id: tenantId })
      .orderBy('start_date', 'asc');
  }
}
