import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeService } from './tournament-code.service'; @Injectable() export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(TournamentCodeScheduler.name); private attachTimer?: NodeJS.Timeout; private expireTimer?: NodeJS.Timeout; private refillTimer?: NodeJS.Timeout; constructor( private readonly tournamentCodeService: TournamentCodeService, private readonly autoProvisionService: TournamentCodeAutoProvisionService, ) {} public onModuleInit() { this.attachTimer = setInterval(() => { void this.attachPending(); }, 30_000); this.expireTimer = setInterval(() => { void this.markExpired(); }, 60 * 60 * 1000); if (isAutoProvisionEnabled()) { this.refillTimer = setInterval(() => { void this.ensureVendorPool(); }, 5 * 60 * 1000); } this.attachTimer.unref?.(); this.expireTimer.unref?.(); this.refillTimer?.unref?.(); void this.attachPending(); void this.markExpired(); if (isAutoProvisionEnabled()) { void this.ensureVendorPool(); } } public onModuleDestroy() { if (this.attachTimer) clearInterval(this.attachTimer); if (this.expireTimer) clearInterval(this.expireTimer); if (this.refillTimer) clearInterval(this.refillTimer); } private async attachPending() { try { const touched = await this.tournamentCodeService.attachPendingMatches(); if (touched > 0) { this.logger.debug(`Attached tournament codes for ${touched} matches.`); } } catch (error) { this.logger.warn( `Failed to attach pending tournament codes: ${ error instanceof Error ? error.message : error }`, ); } } private async markExpired() { try { await this.tournamentCodeService.markExpired(); } catch (error) { this.logger.warn( `Failed to mark expired tournament codes: ${ error instanceof Error ? error.message : error }`, ); } } private async ensureVendorPool() { try { await this.autoProvisionService.ensurePool(); } catch (error) { this.logger.warn( `Failed to auto-provision tournament codes: ${ error instanceof Error ? error.message : error }`, ); } } } function isAutoProvisionEnabled(): boolean { const raw = process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED ?.trim() .toLowerCase(); return raw !== 'false' && raw !== '0' && raw !== 'off'; }