import type { PageServerLoad } from './$types';
import { getAuthTokens, authenticatedFetch, handleApiResponse } 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',
			items: [],
			total: 0,
			page: 1,
			page_size: 50,
			companies: parentData.companies || []
		};
	}

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

		// 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',
				items: [],
				total: 0,
				page: page,
				page_size: pageSize,
				companies: parentData.companies || []
			};
		}

		// Construir URL con parámetros
		let apiUrl = `v1/a76/clients-providers?company_id=${companyId}&page=${page}&page_size=${pageSize}`;

		const type = url.searchParams.get('type');
		if (type && type !== 'both') {
			apiUrl += `&type=${type}`;
		}

		// Usar authenticatedFetch para manejar automáticamente el refresh de tokens
		const response = await authenticatedFetch(
			apiUrl,
			{},
			cookies,
			fetch
		);

		const result = await handleApiResponse(response);

		if (result.error) {
			console.error('📊 [Clients&Providers] API Error:', result.error);

			return {
				error: result.error,
				items: [],
				total: 0,
				page: page,
				page_size: pageSize,
				companies: parentData.companies || [],
				currentCompanyId: companyId
			};
		}

		const data = result.data;

		return {
			items: data.items || [],
			total: data.total || 0,
			page: data.page || page,
			page_size: data.page_size || pageSize,
			error: null,
			companies: parentData.companies || [],
			currentCompanyId: companyId
		};
	} catch (error) {
		console.error('📊 [Clients&Providers] Load error:', error);
		return {
			error: 'Error loading data',
			items: [],
			total: 0,
			page: 1,
			page_size: 50,
			companies: parentData.companies || []
		};
	}
};
