"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.setCronSchedule = setCronSchedule;
exports.clearCronSchedule = clearCronSchedule;
exports.getCronStatus = getCronStatus;
const yamlDb = __importStar(require("../../services/yaml-workflow/db"));
const cron_1 = require("../../services/cron");
const helpers_1 = require("./helpers");
/**
 * Set or update the cron schedule for a YAML workflow.
 *
 * Persists the schedule in the DB and restarts the in-process cron timer via the
 * cron registry so the change takes effect immediately.
 *
 * @param input.id — UUID of the workflow to schedule
 * @param input.cron_schedule — cron expression (e.g. "0 * * * *")
 * @param input.cron_envelope — optional payload passed to each scheduled invocation
 * @param input.execute_as — optional identity override for scheduled executions
 * @returns `{ status: 200, data: YamlWorkflow }` the updated workflow record with cron fields set
 */
async function setCronSchedule(input) {
    try {
        const wf = await yamlDb.getYamlWorkflow(input.id);
        if (!wf) {
            return { status: 404, error: 'YAML workflow not found' };
        }
        if (!input.cron_schedule || typeof input.cron_schedule !== 'string') {
            return { status: 400, error: 'cron_schedule is required' };
        }
        const updated = await yamlDb.updateCronSchedule(wf.id, input.cron_schedule.trim(), input.cron_envelope ?? null, input.execute_as ?? null);
        if (updated) {
            await cron_1.cronRegistry.restartYamlCron(updated);
        }
        return { status: 200, data: updated };
    }
    catch (err) {
        if ((0, helpers_1.isNotFoundError)(err)) {
            return { status: 404, error: 'YAML workflow not found' };
        }
        return { status: 500, error: err.message };
    }
}
/**
 * Remove the cron schedule from a YAML workflow.
 *
 * Stops the in-process cron timer first, then clears the schedule fields in the DB.
 *
 * @param input.id — UUID of the workflow to unschedule
 * @returns `{ status: 200, data: YamlWorkflow }` the updated workflow record with cron fields cleared
 */
async function clearCronSchedule(input) {
    try {
        const wf = await yamlDb.getYamlWorkflow(input.id);
        if (!wf) {
            return { status: 404, error: 'YAML workflow not found' };
        }
        await cron_1.cronRegistry.stopYamlCron(wf.id);
        const updated = await yamlDb.clearCronSchedule(wf.id);
        return { status: 200, data: updated };
    }
    catch (err) {
        if ((0, helpers_1.isNotFoundError)(err)) {
            return { status: 404, error: 'YAML workflow not found' };
        }
        return { status: 500, error: err.message };
    }
}
/**
 * List all YAML workflows that have a cron schedule, with their live timer status.
 *
 * Fetches all cron-scheduled workflows from the DB and cross-references with the
 * in-process cron registry to determine which timers are actually running.
 *
 * @returns `{ status: 200, data: { schedules: Array<{ id, name, graph_topic, app_id, cron_schedule, execute_as, active }> } }`
 */
async function getCronStatus() {
    try {
        const workflows = await yamlDb.getCronScheduledWorkflows();
        const activeTypes = cron_1.cronRegistry.activeWorkflowTypes;
        const schedules = workflows.map((wf) => ({
            id: wf.id,
            name: wf.name,
            graph_topic: wf.graph_topic,
            app_id: wf.app_id,
            cron_schedule: wf.cron_schedule,
            execute_as: wf.execute_as,
            active: activeTypes.includes(`yaml:${wf.id}`),
        }));
        return { status: 200, data: { schedules } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
