"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fastifyApolloHandler = void 0;
const node_stream_1 = require("node:stream");
const fastify_request_to_graphql_request_js_1 = require("./fastify-request-to-graphql-request.js");
const utils_js_1 = require("./utils.js");
function fastifyApolloHandler(apollo, options) {
    if (apollo === undefined || apollo === null || !(0, utils_js_1.isApolloServerLike)(apollo)) {
        throw new TypeError("You must pass in an instance of `ApolloServer`.");
    }
    apollo.assertStarted("fastifyApolloHandler()");
    const defaultContext = () => Promise.resolve({});
    const contextFunction = options?.context ?? defaultContext;
    return async (request, reply) => {
        const httpGraphQLResponse = await apollo.executeHTTPGraphQLRequest({
            httpGraphQLRequest: (0, fastify_request_to_graphql_request_js_1.fastifyRequestToGraphQLRequest)(request),
            context: () => contextFunction(request, reply),
        });
        const { headers, body, status } = httpGraphQLResponse;
        for (const [headerKey, headerValue] of headers) {
            void reply.header(headerKey, headerValue);
        }
        void reply.code(status === undefined ? 200 : status);
        if (body.kind === "complete") {
            return body.string;
        }
        const readable = node_stream_1.Readable.from(body.asyncIterator);
        return reply.send(readable);
    };
}
exports.fastifyApolloHandler = fastifyApolloHandler;
