"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.listWorkflowConfigs = listWorkflowConfigs;
exports.getWorkflowConfig = getWorkflowConfig;
exports.upsertWorkflowConfig = upsertWorkflowConfig;
exports.deleteWorkflowConfig = deleteWorkflowConfig;
const configService = __importStar(require("../../services/config"));
const cron_1 = require("../../services/cron");
const ltconfig_1 = require("../../modules/ltconfig");
/**
 * List all registered workflow configurations.
 *
 * @returns `{ status: 200, data: { workflows: LTWorkflowConfig[] } }`
 */
async function listWorkflowConfigs() {
    try {
        const configs = await configService.listWorkflowConfigs();
        return { status: 200, data: { workflows: configs } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Get a single workflow configuration by type.
 *
 * @param input.type — workflow type name (e.g. `"reviewContent"`)
 * @returns `{ status: 200, data: <config> }` or 404
 */
async function getWorkflowConfig(input) {
    try {
        const config = await configService.getWorkflowConfig(input.type);
        if (!config) {
            return { status: 404, error: 'Workflow config not found' };
        }
        return { status: 200, data: config };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Create or replace a workflow configuration.
 *
 * Invalidates the config cache and restarts the cron schedule if one
 * is defined. Idempotent — safe to call repeatedly with the same input.
 *
 * @param input.type — workflow type name
 * @param input.invocable — whether the workflow can be started via the API
 * @param input.task_queue — HotMesh task queue
 * @param input.default_role — default escalation role
 * @param input.description — human-readable description
 * @param input.execute_as — service account for proxy invocation
 * @param input.roles — roles that can resolve escalations
 * @param input.invocation_roles — roles that can invoke this workflow
 * @param input.consumes — workflow types whose data this workflow consumes
 * @param input.tool_tags — MCP tool tags for discovery
 * @param input.envelope_schema — JSON Schema for envelope.data validation
 * @param input.resolver_schema — JSON Schema for resolver payload validation
 * @param input.cron_schedule — cron expression for scheduled execution
 * @returns `{ status: 200, data: <saved config> }`
 */
async function upsertWorkflowConfig(input) {
    try {
        // Validate cron expression before persisting
        if (input.cron_schedule) {
            const { validateCronSchedule } = await Promise.resolve().then(() => __importStar(require('../../services/cron')));
            validateCronSchedule(input.cron_schedule);
        }
        const config = await configService.upsertWorkflowConfig({
            workflow_type: input.type,
            invocable: input.invocable ?? false,
            task_queue: input.task_queue ?? null,
            default_role: input.default_role ?? 'reviewer',
            description: input.description ?? null,
            execute_as: input.execute_as ?? null,
            roles: input.roles ?? [],
            invocation_roles: input.invocation_roles ?? [],
            consumes: input.consumes ?? [],
            tool_tags: input.tool_tags ?? [],
            envelope_schema: input.envelope_schema ?? null,
            resolver_schema: input.resolver_schema ?? null,
            cron_schedule: input.cron_schedule ?? null,
        });
        ltconfig_1.ltConfig.invalidate();
        await cron_1.cronRegistry.restartCron(config);
        return { status: 200, data: config };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Delete a workflow configuration.
 *
 * Removes the config record and invalidates the cache. Active workers
 * continue running — this only removes the config/interceptor binding.
 *
 * @param input.type — workflow type name
 * @returns `{ status: 200, data: { deleted: true, workflow_type } }` or 404
 */
async function deleteWorkflowConfig(input) {
    try {
        const deleted = await configService.deleteWorkflowConfig(input.type);
        if (!deleted) {
            return { status: 404, error: 'Workflow config not found' };
        }
        ltconfig_1.ltConfig.invalidate();
        return { status: 200, data: { deleted: true, workflow_type: input.type } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
