"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFastifyHandler = createFastifyHandler;
/**
 * Fastify adapter for the MCP transport core (operations port, #614).
 *
 * Maps Fastify's `(request, reply)` ↔ the transport's normalized
 * Request/Response shape. The route is registered with the
 * `authAndEnsureUserOnRequest` preValidation hook, so the authenticated
 * user lands on `request.hdb_user` before this handler runs.
 *
 * Fastify auto-parses JSON request bodies; we re-stringify so the core's
 * `parseMessage` sees the raw envelope it expects. The round-trip is
 * cheap for the small JSON-RPC frames in the MCP wire format and keeps
 * the core framework-agnostic.
 */
const transport_ts_1 = require("../transport.js");
function createFastifyHandler(profile) {
    return async function mcpFastifyHandler(request, reply) {
        const norm = {
            method: request.method,
            headers: normalizeHeaders(request.headers),
            // Fastify has already parsed the JSON body into an object via its
            // preParsing pipeline. Pass it through directly — the transport
            // core's parseMessage accepts both strings and parsed values, so we
            // avoid an unnecessary stringify/re-parse round trip on the hot path.
            body: request.body,
            user: request.hdb_user?.username ?? '',
            userObject: (request.hdb_user ?? undefined),
            profile,
        };
        const res = await (0, transport_ts_1.handleMcpRequest)(norm);
        reply.code(res.status);
        for (const [name, value] of Object.entries(res.headers)) {
            reply.header(name, value);
        }
        if (res.jsonBody !== undefined) {
            if (!res.headers['Content-Type'] && !res.headers['content-type']) {
                reply.header('Content-Type', 'application/json');
            }
            reply.send(res.jsonBody);
            return;
        }
        if (res.sseIterable !== undefined) {
            // Reserved for #619 (server-push GET stream). Fastify will iterate
            // the async iterable and write SSE frames via the contentTypes
            // serializer at `server/serverHelpers/contentTypes.ts:128-162`.
            if (!res.headers['Content-Type'] && !res.headers['content-type']) {
                reply.header('Content-Type', 'text/event-stream');
            }
            reply.header('Cache-Control', 'no-store');
            reply.send(res.sseIterable);
            return;
        }
        // 202/204/4xx with empty body.
        reply.send();
    };
}
function normalizeHeaders(headers) {
    const out = {};
    for (const [name, value] of Object.entries(headers)) {
        out[name.toLowerCase()] = Array.isArray(value) ? value[0] : value;
    }
    return out;
}
//# sourceMappingURL=fastify.js.map