import type { Handle } from '@sveltejs/kit';

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend:3000';

export const handle: Handle = async ({ event, resolve }) => {
	// Proxy API requests to the backend
	if (event.url.pathname.startsWith('/api')) {
		const backendUrl = `${BACKEND_URL}${event.url.pathname}${event.url.search}`;
		
		// Forward the request to the backend
		const response = await fetch(backendUrl, {
			method: event.request.method,
			headers: {
				...Object.fromEntries(event.request.headers),
				host: new URL(BACKEND_URL).host
			},
			body: event.request.body,
			// @ts-expect-error - duplex is needed for streaming requests
			duplex: 'half'
		});

		return new Response(response.body, {
			status: response.status,
			headers: response.headers
		});
	}

	return resolve(event);
};
