import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { WalletApplicationService } from '@/application/services';

/**
 * 过期奖励处理定时任务
 *
 * 每分钟执行一次，处理已过期的待领取奖励：
 * 1. 扫描 pending_rewards 表中 status=PENDING 且 expire_at < now 的记录
 * 2. 标记为 EXPIRED
 * 3. 将过期金额转移到总部社区账户 (S0000000001)
 */
@Injectable()
export class ExpiredRewardsScheduler {
  private readonly logger = new Logger(ExpiredRewardsScheduler.name);

  constructor(
    private readonly walletService: WalletApplicationService,
  ) {}

  /**
   * 每分钟执行一次过期奖励处理
   */
  @Cron(CronExpression.EVERY_MINUTE)
  async handleExpiredRewards(): Promise<void> {
    this.logger.log('Starting expired rewards processing job...');

    try {
      const result = await this.walletService.processExpiredRewards(100);

      if (result.processedCount > 0) {
        this.logger.log(
          `Expired rewards job completed: processed=${result.processedCount}, ` +
          `totalExpiredUsdt=${result.totalExpiredUsdt}, ` +
          `transferredToHQ=${result.transferredToHeadquarters}`,
        );
      } else {
        this.logger.debug('No expired rewards to process');
      }
    } catch (error) {
      this.logger.error('Failed to process expired rewards', error);
    }
  }

  /**
   * 手动触发过期处理（用于测试或管理员操作）
   */
  async triggerManually(batchSize = 100): Promise<{
    processedCount: number;
    totalExpiredUsdt: number;
    transferredToHeadquarters: number;
  }> {
    this.logger.log('Manually triggered expired rewards processing');
    return this.walletService.processExpiredRewards(batchSize);
  }
}
