import type { PageServerLoad } from './$types';
import { getAuthTokens, authenticatedFetch } from '$lib/server/api';

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
	await parent();
	const { accessToken } = getAuthTokens(cookies);

	if (!accessToken) {
		return {
			error: 'No authenticated',
			exchange_rates: { items: [], total: 0, page: 1, page_size: 10, pages: 0 }
		};
	}

	try {
		const page = Number(url.searchParams.get('page')) || 1;
		const pageSize = Number(url.searchParams.get('pageSize')) || 10;
		const filters: Record<string, string> = {};

		// Obtener company_id
		const parentData = await parent();
		const cookieCompanyId = cookies.get('active_company_id');
		const companyId = cookieCompanyId
			? parseInt(cookieCompanyId)
			: parentData.companies?.[0]?.id;

		if (!companyId) {
			return {
				error: 'No company selected',
				exchange_rates: { items: [], total: 0, page, page_size: pageSize, pages: 0 }
			};
		}

		const queryParams = new URLSearchParams({
			page: page.toString(),
			page_size: pageSize.toString(),
			company_id: companyId.toString(),
			...filters
		});

		const response = await authenticatedFetch(
			`v1/a76/exchange-rate/?${queryParams.toString()}`,
			{ 
				method: 'GET',
				cache: 'no-store'
			},
			cookies,
			fetch
		);

		if (!response.ok) {
			let errorMessage = 'Failed to load exchange rates';
			try {
				const errorData = await response.json();
				errorMessage = errorData.detail || errorData.message || errorMessage;
			} catch (e) {
				errorMessage = response.statusText || errorMessage;
			}

			return {
				error: errorMessage,
				status: response.status,
				exchange_rates: { items: [], total: 0, page, page_size: pageSize, pages: 0 }
			};
		}

		return { exchange_rates: await response.json(), status: 200 };
	} catch (error: any) {
		console.error('Error loading exchange rates:', error);
		return {
			error: error.message || 'Error loading',
			status: error.status || 500,
			exchange_rates: { items: [], total: 0, page: 1, page_size: 10, pages: 0 }
		};
	}
};
