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

const API_BACKEND = process.env.VITE_API_URL || 'http://localhost:8095';

export const handle: Handle = async ({ event, resolve }) => {
	if (event.url.pathname.startsWith('/api/') || event.url.pathname.startsWith('/images/')) {
		const targetUrl = `${API_BACKEND}${event.url.pathname}${event.url.search}`;

		const headers = new Headers();
		for (const [key, value] of event.request.headers.entries()) {
			if (['authorization', 'content-type', 'cookie', 'x-api-key', 'x-telegram-user-id'].includes(key.toLowerCase())) {
				headers.set(key, value);
			}
		}

		try {
			const response = await fetch(targetUrl, {
				method: event.request.method,
				headers,
				body: event.request.method !== 'GET' && event.request.method !== 'HEAD'
					? await event.request.arrayBuffer()
					: undefined,
			});

			return new Response(response.body, {
				status: response.status,
				headers: response.headers,
			});
		} catch (err) {
			console.error('Proxy error:', err);
			return new Response(JSON.stringify({ error: 'Backend unavailable' }), {
				status: 502,
				headers: { 'Content-Type': 'application/json' },
			});
		}
	}

	return resolve(event);
};
