import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { UserTaggingService } from '../../application/services/user-tagging.service';
import { AudienceSegmentService } from '../../application/services/audience-segment.service';

/**
 * 自动标签同步定时任务
 * 负责定期执行：
 * 1. 自动标签同步（根据规则给用户打标签）
 * 2. 过期标签清理
 * 3. 人群包预估用户数更新
 */
@Injectable()
export class AutoTagSyncJob implements OnModuleInit {
  private readonly logger = new Logger(AutoTagSyncJob.name);
  private isRunning = false;

  constructor(
    private readonly taggingService: UserTaggingService,
    private readonly segmentService: AudienceSegmentService,
  ) {}

  onModuleInit() {
    this.logger.log('AutoTagSyncJob initialized');
  }

  /**
   * 每天凌晨 2 点执行自动标签同步
   */
  @Cron('0 2 * * *')
  async syncAutoTags(): Promise<void> {
    if (this.isRunning) {
      this.logger.warn('Auto tag sync is already running, skipping...');
      return;
    }

    this.isRunning = true;
    this.logger.log('Starting auto tag sync...');

    try {
      const result = await this.taggingService.syncAllAutoTags({
        batchSize: 100,
        onProgress: (processed, total) => {
          if (processed % 1000 === 0) {
            this.logger.log(`Auto tag sync progress: ${processed}/${total}`);
          }
        },
      });

      this.logger.log(
        `Auto tag sync completed: ${result.processed}/${result.total} users processed, ${result.errors.length} errors`,
      );

      // 记录统计信息
      const addedCount = result.results.reduce(
        (sum, r) => sum + r.added.length,
        0,
      );
      const removedCount = result.results.reduce(
        (sum, r) => sum + r.removed.length,
        0,
      );

      this.logger.log(
        `Auto tag sync stats: ${addedCount} tags added, ${removedCount} tags removed`,
      );
    } catch (error) {
      this.logger.error(`Auto tag sync failed: ${error}`);
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * 每天凌晨 3 点清理过期标签
   */
  @Cron('0 3 * * *')
  async cleanExpiredTags(): Promise<void> {
    this.logger.log('Starting expired tag cleanup...');

    try {
      const count = await this.taggingService.cleanExpiredTags();
      this.logger.log(`Cleaned ${count} expired tag assignments`);
    } catch (error) {
      this.logger.error(`Expired tag cleanup failed: ${error}`);
    }
  }

  /**
   * 每天凌晨 4 点更新人群包预估用户数
   */
  @Cron('0 4 * * *')
  async refreshSegmentEstimates(): Promise<void> {
    this.logger.log('Starting segment estimate refresh...');

    try {
      await this.segmentService.recalculateAllEstimatedUsers();
      this.logger.log('Segment estimate refresh completed');
    } catch (error) {
      this.logger.error(`Segment estimate refresh failed: ${error}`);
    }
  }

  /**
   * 手动触发自动标签同步（供 API 调用）
   */
  async triggerSync(): Promise<{
    processed: number;
    total: number;
    errors: number;
  }> {
    if (this.isRunning) {
      throw new Error('Auto tag sync is already running');
    }

    this.isRunning = true;

    try {
      const result = await this.taggingService.syncAllAutoTags();
      return {
        processed: result.processed,
        total: result.total,
        errors: result.errors.length,
      };
    } finally {
      this.isRunning = false;
    }
  }

  /**
   * 获取同步状态
   */
  getSyncStatus(): { isRunning: boolean } {
    return { isRunning: this.isRunning };
  }
}
