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');

		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 se encontró una compañía seleccionada',
				items: [],
				total: 0,
				page,
				page_size: pageSize
			};
		}

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

		if (!response.ok) {
			const errorText = await response.text();
			console.error('📊 [CustomsSections] API Error:', {
				status: response.status,
				statusText: response.statusText,
				error: errorText
			});
			
			return {
				status: response.status,
				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,
			companyId,
			status: response.status,
			error: null
		};
	} catch (error) {
		console.error('📊 [CustomsSections] Load error:', error);
		return {
			error: 'Error loading data',
			items: [],
			total: 0,
			page: 1,
			page_size: 50
		};
	}
};
