import type { RequestHandler } from './$types';
import { getAccessTokenFromCookies } from '$lib/server/access-token-cookie';

export const GET: RequestHandler = async ({ cookies, url }) => {
	const token = getAccessTokenFromCookies(cookies);

	// Obtener company_id de la cookie
	const companyId = cookies.get('active_company_id');

	if (!companyId) {
		return new Response(
			JSON.stringify({ error: 'No company selected' }),
			{
				status: 400,
				headers: {
					'Content-Type': 'application/json'
				}
			}
		);
	}

	// 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 and add company_id
	const searchParams = new URLSearchParams(url.search);
	searchParams.set('company_id', companyId);
	const queryString = searchParams.toString();

	try {
		const fetchUrl = `${baseUrl}v1/a76/classes?${queryString}`;

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

		if (!response.ok) {
			const errorText = await response.text();
			console.error('Error response from backend:', errorText);
			return new Response(
				JSON.stringify({
					error: 'Failed to fetch classes',
					details: errorText
				}),
				{
					status: response.status,
					headers: {
						'Content-Type': 'application/json'
					}
				}
			);
		}

		const data = await response.json();
		return new Response(JSON.stringify(data), {
			status: 200,
			headers: {
				'Content-Type': 'application/json'
			}
		});
	} catch (error) {
		console.error('Error in classes API route:', error);
		return new Response(
			JSON.stringify({
				error: 'Internal server error',
				message: error instanceof Error ? error.message : 'Unknown error'
			}),
			{
				status: 500,
				headers: {
					'Content-Type': 'application/json'
				}
			}
		);
	}
};
