"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWorkflowConfig = getWorkflowConfig;
exports.listWorkflowConfigs = listWorkflowConfigs;
const db_1 = require("../../lib/db");
const sql_1 = require("./sql");
async function getWorkflowConfig(workflowType) {
    const pool = (0, db_1.getPool)();
    const { rows: wfRows } = await pool.query(sql_1.GET_WORKFLOW, [workflowType]);
    if (wfRows.length === 0)
        return null;
    const wf = wfRows[0];
    const [rolesResult, invocationRolesResult] = await Promise.all([
        pool.query(sql_1.GET_WORKFLOW_ROLES, [workflowType]),
        pool.query(sql_1.GET_WORKFLOW_INVOCATION_ROLES, [workflowType]),
    ]);
    return {
        workflow_type: wf.workflow_type,
        invocable: wf.invocable,
        task_queue: wf.task_queue,
        default_role: wf.default_role,
        description: wf.description,
        roles: rolesResult.rows.map((r) => r.role),
        invocation_roles: invocationRolesResult.rows.map((r) => r.role),
        consumes: wf.consumes || [],
        tool_tags: wf.tool_tags || [],
        envelope_schema: wf.envelope_schema ?? null,
        resolver_schema: wf.resolver_schema ?? null,
        cron_schedule: wf.cron_schedule ?? null,
        execute_as: wf.execute_as ?? null,
    };
}
async function listWorkflowConfigs() {
    const pool = (0, db_1.getPool)();
    const [wfResult, rolesResult, invocationRolesResult] = await Promise.all([
        pool.query(sql_1.LIST_ALL_WORKFLOWS),
        pool.query(sql_1.LIST_ALL_ROLES),
        pool.query(sql_1.LIST_ALL_INVOCATION_ROLES),
    ]);
    // Index sub-entities by workflow_type
    const rolesMap = new Map();
    for (const r of rolesResult.rows) {
        if (!rolesMap.has(r.workflow_type))
            rolesMap.set(r.workflow_type, []);
        rolesMap.get(r.workflow_type).push(r.role);
    }
    const invocationRolesMap = new Map();
    for (const r of invocationRolesResult.rows) {
        if (!invocationRolesMap.has(r.workflow_type))
            invocationRolesMap.set(r.workflow_type, []);
        invocationRolesMap.get(r.workflow_type).push(r.role);
    }
    return wfResult.rows.map((wf) => ({
        workflow_type: wf.workflow_type,
        invocable: wf.invocable,
        task_queue: wf.task_queue,
        default_role: wf.default_role,
        description: wf.description,
        roles: rolesMap.get(wf.workflow_type) || [],
        invocation_roles: invocationRolesMap.get(wf.workflow_type) || [],
        consumes: wf.consumes || [],
        tool_tags: wf.tool_tags || [],
        envelope_schema: wf.envelope_schema ?? null,
        resolver_schema: wf.resolver_schema ?? null,
        cron_schedule: wf.cron_schedule ?? null,
        execute_as: wf.execute_as ?? null,
    }));
}
