import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ContractSigningService } from '../services/contract-signing.service';

/**
 * 合同签署超时定时任务
 *
 * 每5分钟扫描一次过期未签署的合同任务
 * 将其状态标记为 UNSIGNED_TIMEOUT
 */
@Injectable()
export class ContractSigningTimeoutJob {
  private readonly logger = new Logger(ContractSigningTimeoutJob.name);

  constructor(private readonly contractSigningService: ContractSigningService) {}

  /**
   * 每5分钟执行一次
   */
  @Cron(CronExpression.EVERY_5_MINUTES)
  async handleTimeout(): Promise<void> {
    this.logger.debug('[CONTRACT-TIMEOUT] Starting timeout check...');

    try {
      const count = await this.contractSigningService.handleExpiredTasks();

      if (count > 0) {
        this.logger.log(`[CONTRACT-TIMEOUT] Processed ${count} expired signing tasks`);
      } else {
        this.logger.debug('[CONTRACT-TIMEOUT] No expired tasks found');
      }
    } catch (error) {
      this.logger.error('[CONTRACT-TIMEOUT] Error processing expired tasks:', error);
    }
  }
}
