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
	const parentData = await parent();
	
	const { accessToken } = getAuthTokens(cookies);
	
	if (!accessToken) {
		return {
			error: 'No authenticated',
			brokers: [],
			companies: parentData.companies || []
		};
	}

	try {
		// Obtener company_id de múltiples fuentes (en orden de prioridad):
		// 1. URL query param (permite cambiar vía navegación)
		// 2. Cookie active_company_id (setted por el team-switcher)
		// 3. Primera compañía del usuario (fallback)
		const companyIdParam = url.searchParams.get('company_id');
		const cookieCompanyId = cookies.get('active_company_id');
		
		const companyId = companyIdParam 
			? parseInt(companyIdParam)
			: cookieCompanyId
				? parseInt(cookieCompanyId)
				: parentData.companies?.[0]?.id;
		
		if (!companyId) {
			return {
				error: 'No company selected',
				brokers: [],
				companies: parentData.companies || []
			};
		}

		// Usar authenticatedFetch para manejar automáticamente el refresh de tokens
		const response = await authenticatedFetch(
			`v1/a76/customs-brokers?company_id=${companyId}`,
			{},
			cookies,
			fetch
		);

		if (!response.ok) {
			const errorText = await response.text();
			console.error('📊 [CustomsBrokers] API Error:', {
				status: response.status,
				statusText: response.statusText,
				error: errorText
			});
			
			return {
				error: `Error ${response.status}: ${response.statusText}`,
				brokers: [],
				companies: parentData.companies || [],
				currentCompanyId: companyId
			};
		}

		const data = await response.json();

		// El endpoint devuelve un objeto con items, total, page, page_size
		// Extraer el array de items
		const brokers = Array.isArray(data) ? data : (data.items || []);

		return {
			brokers: brokers,
			error: null,
			companies: parentData.companies || [],
			currentCompanyId: companyId
		};
	} catch (error) {
		console.error('📊 [CustomsBrokers] Load error:', error);
		return {
			error: 'Error loading data',
			brokers: [],
			companies: parentData.companies || []
		};
	}
};
