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

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
	// Esperar a que el layout padre valide/refresque el token
	await parent();
	
	const { accessToken } = getAuthTokens(cookies);
	
	if (!accessToken) {
		return {
			error: 'No authenticated',
			items: [],
			total: 0,
			page: 1,
			page_size: 50
		};
	}

	try {
		// Obtener parámetros de paginación de la URL
		const page = parseInt(url.searchParams.get('page') || '1');
		const pageSize = parseInt(url.searchParams.get('page_size') || '50');

		// Usar authenticatedFetch para manejar automáticamente el refresh de tokens
		const response = await authenticatedFetch(
			`v1/public/reference_data/incoterms/?page=${page}&page_size=${pageSize}`,
			{},
			cookies,
			fetch
		);

		if (!response.ok) {
			const errorText = await response.text();
			console.error('📊 [Incoterms] API Error:', {
				status: response.status,
				statusText: response.statusText,
				error: errorText
			});
			
			return {
				error: `Error ${response.status}: ${response.statusText}`,
				items: [],
				total: 0,
				page: page,
				page_size: pageSize
			};
		}

		const data = await response.json();

		return {
			items: data.items || [],
			total: data.total || 0,
			page: data.page || page,
			page_size: data.page_size || pageSize,
			error: null
		};
	} catch (error) {
		console.error('📊 [Incoterms] Load error:', error);
		return {
			error: 'Error loading data',
			items: [],
			total: 0,
			page: 1,
			page_size: 50
		};
	}
};
