"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FlowActivationTask = void 0;
exports.getRecordIdsByTable = getRecordIdsByTable;
const FLOW_TABLE = 'sys_hub_flow';
const ACTION_TABLE = 'sys_hub_action_type_definition';
async function activateFlows(context) {
    const { instanceClient, logger, config, recordIds } = context;
    const { scopeId } = config;
    if (!instanceClient) {
        logger.debug('No instance connection available, skipping flow activation');
        return;
    }
    const flowAndSubflowIds = recordIds?.[FLOW_TABLE] ?? [];
    const actionIds = recordIds?.[ACTION_TABLE] ?? [];
    if (flowAndSubflowIds.length === 0 && actionIds.length === 0) {
        logger.debug('No flows, subflows, or actions found in project, skipping flow activation');
        return;
    }
    logger.debug(`Activating flows... (${flowAndSubflowIds.length} flow/subflow(s), ${actionIds.length} action(s))`);
    const response = await instanceClient.fetch('api/now/wfa_fluent/activate_flows', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            flows: flowAndSubflowIds,
            actions: actionIds,
        }),
    }, new URLSearchParams({ sysparm_transaction_scope: scopeId }));
    // 422 = all flows failed — still returns a valid result body
    // Any other non-OK status (400, 401, 403, 500, etc.) is an error
    if (!response.ok && response.status !== 422) {
        const body = await response.json().catch(() => null);
        const msg = body?.result?.error?.message ?? body?.error?.message ?? body?.message ?? response.statusText;
        // Instances without the endpoint return 400 with "does not represent any resource"
        if (msg.includes('does not represent any resource')) {
            logger.debug('Flow activation endpoint not found. Make sure you have the latest ServiceNow IDE installed on your instance.');
            return;
        }
        throw new Error(`Failed to activate flows: ${msg}`);
    }
    const body = (await response.json());
    const { summary, results } = body.result;
    if (summary.total === 0) {
        logger.debug('No flows to activate');
        return;
    }
    if (summary.failed === 0) {
        logger.info(`Flow activation complete: ${summary.succeeded}/${summary.total} succeeded`);
        return;
    }
    const failures = results.filter((r) => r.status !== 'success');
    const MAX_LOGGED_FAILURES = 5;
    for (const r of failures.slice(0, MAX_LOGGED_FAILURES)) {
        logger.warn(`  Failed: ${r.flow_name ?? r.sys_id} — ${r.message ?? ''}${r.errorMessage ? `: ${r.errorMessage}` : ''}`);
    }
    if (failures.length > MAX_LOGGED_FAILURES) {
        logger.warn(`  ... and ${failures.length - MAX_LOGGED_FAILURES} more`);
    }
    const msg = `Flow activation complete: ${summary.succeeded}/${summary.total} succeeded, ${summary.failed} failed`;
    if (summary.succeeded === 0) {
        throw new Error(msg);
    }
    logger.warn(msg);
}
function getRecordIdsByTable(keysRegistry) {
    const result = {};
    for (const entry of Object.values(keysRegistry.explicit)) {
        if (entry.deleted) {
            continue;
        }
        const entries = (result[entry.table] ??= []);
        entries.push({ sys_id: entry.id, active: '', state: '' });
    }
    return result;
}
exports.FlowActivationTask = {
    name: 'flow-activation',
    skipFlag: 'skipFlowActivation',
    skipFlagDescription: 'Skip activating (publishing) flows after install',
    runFor: 'both',
    run: activateFlows,
};
//# sourceMappingURL=flow-activation.js.map