import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

const BACKEND_URL =
    import.meta.env.VITE_BACKEND_URL || 'http://localhost:8080';

async function proxyRequest(request: Request, path: string) {
    const incomingUrl = new URL(request.url);

    const queryString = incomingUrl.search;

    const url = `${BACKEND_URL}/api/${path}${queryString}`;

    try {
        const headers = new Headers(request.headers);
        headers.delete('host');

        const backendRes = await fetch(url, {
            method: request.method,
            headers,
            body: ['GET', 'HEAD'].includes(request.method)
                ? undefined
                : await request.text()
        });

        // Forward everything transparently
        const resHeaders = new Headers(backendRes.headers);
        return new Response(backendRes.body, {
            status: backendRes.status,
            headers: resHeaders
        });
    } catch (err) {
        console.error('Proxy error:', err);
        return error(502, 'Backend unreachable');
    }
}


export const GET: RequestHandler = ({ request, params }) => proxyRequest(request, params.path);
export const POST: RequestHandler = ({ request, params }) => proxyRequest(request, params.path);
export const PUT: RequestHandler = ({ request, params }) => proxyRequest(request, params.path);
export const DELETE: RequestHandler = ({ request, params }) => proxyRequest(request, params.path);
export const PATCH: RequestHandler = ({ request, params }) => proxyRequest(request, params.path);