import { Injectable, Logger } from "@nestjs/common";
import { Cron } from "@nestjs/schedule";
import { FeederService } from "../modules/feeder/feeder.service";
import { TaskLockService } from "./task-lock.service";

@Injectable()
export class HistoricalResultsSyncTask {
  private readonly logger = new Logger(HistoricalResultsSyncTask.name);

  constructor(
    private readonly feederService: FeederService,
    private readonly taskLock: TaskLockService,
  ) {}

  private shouldSkipInHistoricalMode(jobName: string): boolean {
    if (process.env.FEEDER_MODE === "historical") {
      this.logger.debug(`Skipping ${jobName} in historical feeder mode`);
      return true;
    }
    return false;
  }

  /**
   * Pull yesterday's completed matches into the permanent matches table.
   */
  @Cron("0 8 * * *", { timeZone: "Europe/Istanbul" })
  async syncPreviousDayCompletedMatches() {
    if (this.shouldSkipInHistoricalMode("syncPreviousDayCompletedMatches")) {
      return;
    }

    await this.taskLock.runWithLease(
      "syncPreviousDayCompletedMatches",
      6 * 60 * 60 * 1000,
      async () => {
        this.logger.log(
          "Starting previous-day completed match sync for football and basketball...",
        );

        try {
          await this.feederService.runPreviousDayCompletedMatchesScan();
          this.logger.log("Previous-day completed match sync finished");
        } catch (error: any) {
          this.logger.error(
            `Previous-day completed match sync failed: ${error.message}`,
          );
        }
      },
      this.logger,
    );
  }
}
