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',
            packages: {
                items: [],
                total: 0,
                page: 1,
                page_size: 50,
                pages: 0
            }
        };
    }

    try {
        const page = Number(url.searchParams.get('page')) || 1;
        const pageSize = Number(url.searchParams.get('pageSize')) || 50;
        
        const filters: Record<string, string> = {};
        const key = url.searchParams.get('key');
        const description_es = url.searchParams.get('description_es');

        if (key) filters.key = key;
        if (description_es) filters.description_es = description_es;

        // Obtener company_id de la cookie o usar el primero disponible
        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',
                packages: {
                    items: [],
                    total: 0,
                    page: 1,
                    page_size: 50,
                    pages: 0
                }
            };
        }

        // Construir URL con parámetros
        const queryParams = new URLSearchParams({
            company_id: companyId.toString(),
            page: page.toString(),
            page_size: pageSize.toString(),
            ...filters
        });

        const response = await authenticatedFetch(
            `v1/a76/packages/?${queryParams.toString()}`,
            { method: 'GET' },
            cookies,
            fetch
        );

        if (!response.ok) {
            let errorMessage = 'Failed to load packages';
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                // Si no se puede parsear el JSON, usar el status text o el genérico
                errorMessage = response.statusText || errorMessage;
            }

            return {
                error: errorMessage,
                status: response.status,
                packages: {
                    items: [],
                    total: 0,
                    page: page,
                    page_size: pageSize,
                    pages: 0
                }
            };
        }

        const data = await response.json();
        
        return {
            packages: data,
            status: 200
        };
    } catch (error: any) {
        console.error('Error loading packages:', error);
        return {
            error: error.message || 'Error loading packages',
            status: error.status || 500,
            packages: {
                items: [],
                total: 0,
                page: 1,
                page_size: 50,
                pages: 0
            }
        };
    }
};
