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

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

	// 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
	const searchParams = new URLSearchParams(url.search);
	const queryString = searchParams.toString();

	try {
		const fetchUrl = `${baseUrl}v1/public/reference_data/payment-methods${queryString ? `?${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 payment methods:', error);
		return new Response(
			JSON.stringify({ error: 'Failed to fetch payment methods' }),
			{
				status: 500,
				headers: {
					'Content-Type': 'application/json'
				}
			}
		);
	}
};
