"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupCronHandlers = void 0;
const cron = __importStar(require("node-cron"));
const call_step_file_1 = require("./call-step-file");
const generate_trace_id_1 = require("./generate-trace-id");
const logger_1 = require("./logger");
const setupCronHandlers = (lockedData, eventManager, state, loggerFactory) => {
    const cronJobs = new Map();
    const printer = lockedData.printer;
    const createCronJob = (step) => {
        const { config, filePath } = step;
        const { cron: cronExpression, name: stepName, flows } = config;
        if (!cron.validate(cronExpression)) {
            logger_1.globalLogger.error('[cron handler] invalid cron expression', {
                expression: cronExpression,
                step: stepName,
            });
            return;
        }
        logger_1.globalLogger.debug('[cron handler] setting up cron job', {
            filePath,
            step: stepName,
            cron: cronExpression,
        });
        const task = cron.schedule(cronExpression, async () => {
            const traceId = (0, generate_trace_id_1.generateTraceId)();
            const logger = loggerFactory.create({ traceId, flows, stepName });
            try {
                await (0, call_step_file_1.callStepFile)({
                    contextInFirstArg: true,
                    lockedData,
                    step,
                    eventManager,
                    printer,
                    state,
                    traceId,
                    logger,
                });
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
            }
            catch (error) {
                logger.error('[cron handler] error executing cron job', {
                    error: error.message,
                    step: step.config.name,
                });
            }
        });
        cronJobs.set(step.filePath, task);
    };
    const removeCronJob = (step) => {
        const task = cronJobs.get(step.filePath);
        if (task) {
            task.stop();
            cronJobs.delete(step.filePath);
        }
    };
    const close = () => {
        cronJobs.forEach((task) => task.stop());
        cronJobs.clear();
    };
    lockedData.cronSteps().forEach(createCronJob);
    return { createCronJob, removeCronJob, close };
};
exports.setupCronHandlers = setupCronHandlers;
