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

		// 🛡️ Buscamos el ID de la compañía (indispensable para el backend)
		const companyIdStr = url.searchParams.get('company_id') || 
						   cookies.get('active_company_id') || 
						   cookies.get('activeCompanyId') || 
						   cookies.get('company_id');

		// Si no hay ID, devolvemos estructura vacía y evitamos el 422 de FastAPI
		if (!companyIdStr) {
			return {
				items: [],
				total: 0,
				page: page,
				page_size: pageSize,
				error: null,
				status: 200
			};
		}

		const companyId = parseInt(companyIdStr);

		// 🛡️ Inyectamos el company_id en la Query String
		const response = await authenticatedFetch(
			`v1/public/reference_data/states/?company_id=${companyId}&page=${page}&page_size=${pageSize}`,
			{},
			cookies,
			fetch
		);

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