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');
		headers.delete('content-length');

		let body: BodyInit | undefined;
		const fetchOptions: RequestInit = {};
		if (!['GET', 'HEAD'].includes(request.method)) {
			const contentType = request.headers.get('content-type') || '';
			if (contentType.includes('multipart/form-data')) {
				body = request.body as BodyInit;
				(fetchOptions as Record<string, unknown>).duplex = 'half';
			} else {
				body = await request.text();
			}
		}

		const backendRes = await fetch(url, {
			method: request.method,
			headers,
			body,
			...fetchOptions
		});

		// 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);
