import { Cron } from "croner";
import type { JobInfo } from "../../../types/JobInfo.js";
import { createLog } from "../../logger/logger.js";

export let runningLogisticsCrons: Record<string, Cron> = {};

export const createLogisticsJob = (
    id: string, // this is just the name of the job running
    schedule: string, // `*/30 * * * *`; // default to be every 30 min
    timezone: string,
    task: () => Promise<void>
) => {
    // Destroy existing job if it exists
    if (runningLogisticsCrons[id]) {
        runningLogisticsCrons[id].stop(); // Croner uses .stop() instead of .destroy()
    }

    // Create new job with Croner

    // console.log(timezone);
    // console.log(
    //     new Date().toLocaleString("en-US", { timeZone: "America/Chicago" })
    // );
    runningLogisticsCrons[id] = new Cron(
        schedule,
        {
            timezone: timezone,
            catch: true, // Prevents unhandled rejections
        },
        task
    );

    createLog(
        "info",
        "lst",
        "logistics",
        `Cron setup for ${id}, trigger time: ${schedule}`
    );

    // Optional: Add error handling (Croner emits 'error' events)
    // runningNotifications[id].on("error", (err) => {
    //     console.error(`Job ${id} failed:`, err);
    // });
};

export const getAllLogisticsJobs = (): JobInfo[] => {
    return Object.entries(runningLogisticsCrons).map(([id, job]) => ({
        id,
        schedule: job.getPattern() || "invalid",
        nextRun: job.nextRun() || null,
        lastRun: job.previousRun() || null,
        isRunning: job ? !job.isStopped() : false,
    }));
};

// const removeNotification = (id: any) => {
//     if (runningLogisticsCrons[id]) {
//         runningLogisticsCrons[id].stop();
//         delete runningLogisticsCrons[id];
//     }
// };

export const stopAllLogisticsJobs = () => {
    Object.values(runningLogisticsCrons).forEach((job: any) => job.stop());
    runningLogisticsCrons = {}; // Clear the object
};
