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

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

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

	try {
		const page = parseInt(url.searchParams.get('page') || '1');
		const pageSize = parseInt(url.searchParams.get('page_size') || '50');
		const search = url.searchParams.get('search') || '';
		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,
				status: 400
			};
		}

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

		if (search) {
			params.append('search', search);
		}

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

		if (!response.ok) {
			const message =
				response.status === 403
					? 'No tiene permiso para ver tipos de documento para digitalización'
					: `Error ${response.status}: ${response.statusText}`;
			if (response.status !== 403) {
				const errorText = await response.text();
				console.error('📊 [Document Types Digitization] API Error:', {
					status: response.status,
					statusText: response.statusText,
					error: errorText
				});
			}
			return {
				error: message,
				items: [],
				total: 0,
				page,
				page_size: pageSize,
				status: response.status
			};
		}

		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,
			status: 200
		};
	} catch (error) {
		console.error('📊 [Document Types Digitization] Load error:', error);
		return {
			error: 'Error loading data',
			items: [],
			total: 0,
			page: 1,
			page_size: 50,
			status: 500
		};
	}
};