import cron from "node-cron";

import {
  RUN_CLUB_ACCRUAL,
  RECONCILE_TADBIR_REQUESTS,
  RETRY_PENDING_TADBIR_ISSUANCE_REQUESTS,
} from "$jobs/index.js";

const CRON_TIMEZONE = "Asia/Tehran";

const scheduleJob = (name, expression, job) => {
  return cron.schedule(
    expression,
    async () => {
      try {
        await job();
      } catch (error) {
        console.error(`[cron] ${name} failed`, error);
      }
    },
    {
      timezone: CRON_TIMEZONE,
    },
  );
};

export const startCronJobs = () => {
  scheduleJob(
    "RUN_CLUB_ACCRUAL",
    "15 1 * * *",
    RUN_CLUB_ACCRUAL,
  );

  scheduleJob(
    "RETRY_PENDING_TADBIR_ISSUANCE_REQUESTS",
    "0 9 * * *",
    RETRY_PENDING_TADBIR_ISSUANCE_REQUESTS,
  );

  scheduleJob(
    "RECONCILE_TADBIR_REQUESTS",
    "0 10 * * *",
    RECONCILE_TADBIR_REQUESTS,
  );
};
