import { randomUUID } from 'node:crypto';
import { validateTriggerRequest } from '../services/trigger-types.js';
import { appendTriggerLog } from '../services/trigger-log-store.js';
import { jsonRes } from './workflow-api.js';
const MAX_TRIGGER_BODY_BYTES = 512 * 1024;
export async function readJsonBodyWithLimit(req, maxBytes = MAX_TRIGGER_BODY_BYTES) {
    const chunks = [];
    let total = 0;
    for await (const c of req) {
        const b = c;
        total += b.length;
        if (total > maxBytes)
            throw new Error('body_too_large');
        chunks.push(b);
    }
    if (chunks.length === 0)
        return {};
    return JSON.parse(Buffer.concat(chunks).toString('utf-8'));
}
export function newTriggerId() {
    return `trg_${randomUUID()}`;
}
export async function dispatchTriggerRequest(body, deps) {
    // Both turn and workflow are proxied by botId to the owning daemon's
    // /api/trigger; the daemon IPC handler dispatches turn vs workflow.
    const botId = body.target.botId;
    if (!botId) {
        return {
            status: 400,
            body: { ok: false, errorCode: 'target_required', error: `${body.target.kind} target requires target.botId` },
        };
    }
    const upstream = await deps.proxyToDaemon(botId, '/api/trigger', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(body),
    });
    const text = await upstream.text();
    let parsed;
    try {
        parsed = JSON.parse(text);
    }
    catch {
        parsed = {
            ok: false,
            triggerId: newTriggerId(),
            error: `non-json upstream response (${upstream.status})`,
            errorCode: 'trigger_failed',
        };
    }
    appendTriggerLog({
        triggerId: parsed.triggerId ?? newTriggerId(),
        connectorId: body.source.connectorId,
        action: parsed.ok ? (parsed.action ?? 'delivered') : 'failed',
        status: parsed.ok ? 'ok' : 'error',
        error: parsed.error,
        errorCode: parsed.errorCode,
    });
    return { status: upstream.status, body: parsed };
}
export async function handleDashboardTriggerApi(req, res, deps) {
    let raw;
    try {
        raw = await readJsonBodyWithLimit(req);
    }
    catch (e) {
        const error = e?.message === 'body_too_large' ? 'request body too large' : 'invalid JSON body';
        return jsonRes(res, 400, { ok: false, errorCode: 'bad_json', error });
    }
    const valid = validateTriggerRequest(raw);
    if (!valid.ok)
        return jsonRes(res, valid.status, valid.body);
    const body = valid.request;
    const result = await dispatchTriggerRequest(body, deps);
    return jsonRes(res, result.status, result.body);
}
//# sourceMappingURL=trigger-api.js.map