import { Type } from "@sinclair/typebox";
const TestRequestBody = Type.Object({
    method: Type.String(),
    path: Type.String(),
    headers: Type.Optional(Type.Record(Type.String(), Type.String())),
    body: Type.Optional(Type.String()),
    overrideUrl: Type.Optional(Type.String()),
});
export async function createTestRoutes(fastify, options) {
    const { logger } = options;
    // Test endpoint that proxies requests to the local Zuplo gateway
    fastify.post("/", {
        schema: {
            body: TestRequestBody,
        },
    }, async (request, reply) => {
        const testRequest = request.body;
        const { method, path, headers = {}, body, overrideUrl } = testRequest;
        // Default to localhost:9000 for local Zuplo gateway
        const targetUrl = overrideUrl ?? options.deploymentUrl;
        const fullUrl = `${targetUrl}${path}`;
        logger.info(`Proxying test request: ${method} ${fullUrl}`);
        // Clean headers - remove host and other problematic headers
        const cleanHeaders = {};
        for (const [key, value] of Object.entries(headers)) {
            const lowerKey = key.toLowerCase();
            // Skip headers that shouldn't be forwarded
            if (lowerKey !== "host" && lowerKey !== "connection") {
                cleanHeaders[key] = value;
            }
        }
        // Create fetch options
        const fetchOptions = {
            method,
            headers: cleanHeaders,
        };
        // Add body for non-GET/HEAD requests
        if (body && !["GET", "HEAD"].includes(method.toUpperCase())) {
            fetchOptions.body = body;
        }
        // Make the request to the local gateway
        let response;
        try {
            response = await fetch(fullUrl, fetchOptions);
        }
        catch (err) {
            if (!(err instanceof TypeError)) {
                logger.error({ err, method, fullUrl }, "Error proxying test request");
            }
            else {
                logger.error({ method, fullUrl }, "Error proxying test request");
            }
            // Return a proper problem details response
            const problemDetails = {
                type: "https://zuplo.com/problems/local-gateway-unavailable",
                title: "Local Gateway Unavailable",
                status: 503,
                detail: `Could not connect to the local Zuplo gateway. Make sure your local gateway is running.`,
                instance: fullUrl,
            };
            return reply.status(200).send({
                status: 503,
                statusText: "Service Unavailable",
                headers: {
                    "content-type": "application/problem+json",
                },
                body: JSON.stringify(problemDetails, null, 2),
            });
        }
        // Capture response
        const responseBody = await response.text();
        const responseHeaders = {};
        // Convert headers to plain object
        response.headers.forEach((value, key) => {
            responseHeaders[key] = value;
        });
        // Return test result in the format expected by the frontend
        reply.status(200).send({
            status: response.status,
            statusText: response.statusText,
            headers: responseHeaders,
            body: responseBody,
        });
    });
}
//# sourceMappingURL=test.js.map