import type { RequestHandler } from './$types';

export const GET: RequestHandler = async ({ cookies, url }) => {
	const token = cookies.get('access_token');

	// Configurar la URL de la API usando las variables de entorno
	let apiUrl = process.env.INTERNAL_API_URL;
	if (!apiUrl) {
		apiUrl = process.env.VITE_API_URL;
		// Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR)
		apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend');
	}

	// Normalizar la URL
	const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`;

	// Get query parameters - tariff_fractions es catálogo global (no requiere company_id)
	const searchParams = new URLSearchParams(url.search);
	const queryString = searchParams.toString();

	try {
		const fetchUrl = `${baseUrl}v1/a76/tariff-fractions?${queryString}`;

		const response = await fetch(
			fetchUrl,
			{
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				}
			}
		);

		const data = await response.json();

		if (!response.ok) {
			return new Response(JSON.stringify(data), {
				status: response.status,
				headers: {
					'Content-Type': 'application/json'
				}
			});
		}

		return new Response(JSON.stringify(data), {
			status: 200,
			headers: {
				'Content-Type': 'application/json'
			}
		});
	} catch (error) {
		console.error('Error fetching tariff fractions:', error);
		return new Response(
			JSON.stringify({ error: 'Failed to fetch tariff fractions' }),
			{
				status: 500,
				headers: {
					'Content-Type': 'application/json'
				}
			}
		);
	}
};
