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

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
	await parent();

	const { accessToken } = getAuthTokens(cookies);

	if (!accessToken) {
		return {
			error: 'No authenticated',
			items: [],
			total: 0,
			page: 1,
			page_size: 50
		};
	}

	try {
		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
			};
		}

		const params = new URLSearchParams({
			page: page.toString(),
			page_size: pageSize.toString(),
			company_id: companyId.toString()
		});

		const response = await authenticatedFetch(
			`v1/a76/sectors/?${params.toString()}`,
			{},
			cookies,
			fetch
		);

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