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', classes: { 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 classCode = url.searchParams.get('class_code') || url.searchParams.get('code');
        const description = url.searchParams.get('description'); 

        if (classCode) filters.class_code = classCode; 
        if (description) filters.description = description;
        // ----------------------------------

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

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

        // --- ZONA DE CAMBIO DE ENDPOINT ---
      
        const response = await authenticatedFetch(`v1/a76/parts?${queryParams.toString()}`, { method: 'GET' }, cookies, fetch);

        if (!response.ok) {
            return { error: 'Failed to load', classes: { items: [], total: 0, page, page_size: pageSize, pages: 0 } };
        }

        
        return { classes: await response.json() };

    } catch (error) {
        console.error('Error loading classes:', error);
        return { error: 'Error loading', classes: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
    }
};