import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { LeaderboardApplicationService } from '../services/leaderboard-application.service';
import { LeaderboardType } from '../../domain/value-objects/leaderboard-type.enum';

/**
 * 龙虎榜刷新调度器
 *
 * 定时刷新榜单数据和保存历史快照
 */
@Injectable()
export class LeaderboardRefreshScheduler {
  private readonly logger = new Logger(LeaderboardRefreshScheduler.name);

  constructor(
    private readonly leaderboardService: LeaderboardApplicationService,
  ) {}

  /**
   * 每5分钟刷新所有榜单
   */
  @Cron(CronExpression.EVERY_5_MINUTES)
  async refreshAllLeaderboards() {
    this.logger.log('开始定时刷新龙虎榜...');

    for (const type of Object.values(LeaderboardType)) {
      try {
        await this.leaderboardService.refreshLeaderboard(type as LeaderboardType);
        this.logger.log(`${type} 榜单刷新完成`);
      } catch (error) {
        this.logger.error(`${type} 榜单刷新失败:`, error);
      }
    }

    this.logger.log('龙虎榜定时刷新完成');
  }

  /**
   * 每日00:00保存日榜快照
   */
  @Cron('0 0 0 * * *')
  async snapshotDailyLeaderboard() {
    this.logger.log('保存日榜快照...');
    try {
      await this.leaderboardService.saveSnapshot(LeaderboardType.DAILY);
      this.logger.log('日榜快照保存完成');
    } catch (error) {
      this.logger.error('日榜快照保存失败', error);
    }
  }

  /**
   * 每周一00:00保存周榜快照
   */
  @Cron('0 0 0 * * 1')
  async snapshotWeeklyLeaderboard() {
    this.logger.log('保存周榜快照...');
    try {
      await this.leaderboardService.saveSnapshot(LeaderboardType.WEEKLY);
      this.logger.log('周榜快照保存完成');
    } catch (error) {
      this.logger.error('周榜快照保存失败', error);
    }
  }

  /**
   * 每月1日00:00保存月榜快照
   */
  @Cron('0 0 0 1 * *')
  async snapshotMonthlyLeaderboard() {
    this.logger.log('保存月榜快照...');
    try {
      await this.leaderboardService.saveSnapshot(LeaderboardType.MONTHLY);
      this.logger.log('月榜快照保存完成');
    } catch (error) {
      this.logger.error('月榜快照保存失败', error);
    }
  }
}
