"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.listWorkers = listWorkers;
exports.listDiscoveredWorkflows = listDiscoveredWorkflows;
exports.getCronStatus = getCronStatus;
const configService = __importStar(require("../../services/config"));
const cron_1 = require("../../services/cron");
const db_1 = require("../../lib/db");
const registry_1 = require("../../services/workers/registry");
const sql_1 = require("../../services/pipelines/sql");
/**
 * List active workflow workers with their registration status.
 *
 * @param input.include_system — include system workflows (default: false)
 * @returns `{ status: 200, data: { workers: [{ name, task_queue, registered, system }] } }`
 */
async function listWorkers(input) {
    try {
        const activeWorkers = (0, registry_1.getRegisteredWorkers)();
        const configs = await configService.listWorkflowConfigs();
        const registeredTypes = new Set(configs.map((c) => c.workflow_type));
        const workers = [...activeWorkers.entries()]
            .filter(([name]) => input.include_system || !registry_1.SYSTEM_WORKFLOWS.has(name))
            .sort(([a], [b]) => a.localeCompare(b))
            .map(([name, { taskQueue }]) => ({
            name,
            task_queue: taskQueue,
            registered: registeredTypes.has(name),
            system: registry_1.SYSTEM_WORKFLOWS.has(name),
        }));
        return { status: 200, data: { workers } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Discover all known workflow types from workers, history, and config.
 *
 * Merges three sources: active in-memory workers, historical entities
 * from the durable jobs table, and registered workflow configs. Returns
 * a unified list with status flags for each type.
 *
 * @param input.include_system — include system workflows (default: false)
 * @returns `{ status: 200, data: { workflows: [{ workflow_type, task_queue, registered, active, invocable, ... }] } }`
 */
async function listDiscoveredWorkflows(input) {
    try {
        // 1. Active workers from in-memory registry
        const activeWorkers = (0, registry_1.getRegisteredWorkers)();
        // 2. Historical entities from durable.jobs
        const pool = (0, db_1.getPool)();
        const { rows: entityRows } = await pool.query(sql_1.DISTINCT_ENTITIES_DURABLE);
        const historicalEntities = new Set(entityRows.map((r) => r.entity));
        // 3. Registered configs
        const configs = await configService.listWorkflowConfigs();
        const configMap = new Map(configs.map((c) => [c.workflow_type, c]));
        // Build unified set of all workflow types
        const allTypes = new Set();
        for (const [name] of activeWorkers)
            allTypes.add(name);
        for (const entity of historicalEntities)
            allTypes.add(entity);
        for (const c of configs)
            allTypes.add(c.workflow_type);
        const workflows = [...allTypes]
            .filter((t) => input.include_system || !registry_1.SYSTEM_WORKFLOWS.has(t))
            .sort()
            .map((workflowType) => {
            const config = configMap.get(workflowType);
            const worker = activeWorkers.get(workflowType);
            const hasCertification = !!(config &&
                ((config.roles?.length ?? 0) > 0 ||
                    (config.consumes?.length ?? 0) > 0));
            const tier = !config ? 'durable' : hasCertification ? 'certified' : 'configured';
            return {
                workflow_type: workflowType,
                task_queue: config?.task_queue ?? worker?.taskQueue ?? null,
                tier,
                registered: !!config,
                active: !!worker,
                invocable: config?.invocable ?? !!worker,
                system: registry_1.SYSTEM_WORKFLOWS.has(workflowType),
                description: config?.description ?? null,
                roles: config?.roles ?? [],
                invocation_roles: config?.invocation_roles ?? [],
                execute_as: config?.execute_as ?? null,
            };
        });
        return { status: 200, data: { workflows } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * List all cron-scheduled workflows and their active state.
 *
 * @returns `{ status: 200, data: { schedules: [{ workflow_type, cron_schedule, active, ... }] } }`
 */
async function getCronStatus() {
    try {
        const configs = await configService.listWorkflowConfigs();
        const cronConfigs = configs.filter((c) => c.cron_schedule);
        const activeTypes = cron_1.cronRegistry.activeWorkflowTypes;
        const schedules = cronConfigs.map((c) => ({
            workflow_type: c.workflow_type,
            cron_schedule: c.cron_schedule,
            description: c.description,
            task_queue: c.task_queue,
            invocable: c.invocable,
            active: activeTypes.includes(c.workflow_type),
            envelope_schema: c.envelope_schema,
        }));
        return { status: 200, data: { schedules } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
