import type { FastifyBaseLogger } from 'fastify';
import { processDueBaseballTicketBayAlerts } from '../services/baseball-ticket-bay-service.js';
import { isCurrentWorkServerSlotActive } from '../services/work-server-slot-service.js';

const DEFAULT_INTERVAL_MS = 60_000;

export class BaseballTicketBayWorker {
  private readonly logger: FastifyBaseLogger;

  private timer: ReturnType<typeof setInterval> | null = null;

  private running = false;

  constructor(logger: FastifyBaseLogger) {
    this.logger = logger;
  }

  start() {
    if (this.timer) {
      return;
    }

    this.timer = setInterval(() => {
      void this.tick();
    }, DEFAULT_INTERVAL_MS);
    this.timer.unref?.();
    this.logger.info({ intervalMs: DEFAULT_INTERVAL_MS }, 'Baseball Ticket Bay worker started');
  }

  async stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  private async tick() {
    if (this.running) {
      return;
    }

    if (!(await isCurrentWorkServerSlotActive())) {
      return;
    }

    this.running = true;

    try {
      const results = await processDueBaseballTicketBayAlerts(new Date());
      const executed = results.length;
      const failed = results.filter((item) => !item.ok).length;

      if (executed > 0) {
        this.logger.info({ executed, failed }, 'Baseball Ticket Bay batch processed');
      }
    } catch (error) {
      this.logger.error({ error }, 'Baseball Ticket Bay worker tick failed');
    } finally {
      this.running = false;
    }
  }
}
