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

        const filters: Record<string, string> = {};
        const code = url.searchParams.get('code');
        const description = url.searchParams.get('description');

        if (code) filters.code = code;
        if (description) filters.description = description;

        const queryParams = new URLSearchParams({ 
            page: page.toString(), 
            page_size: pageSize.toString(), 
            company_id: companyId.toString(),
            ...filters 
        });
        
        const response = await authenticatedFetch(`v1/a76/identifiers/?${queryParams.toString()}`, { method: 'GET' }, cookies, fetch);

        if (!response.ok) {
            let errorMessage = 'Failed to load identifiers';
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                errorMessage = response.statusText || errorMessage;
            }

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

        const data = await response.json();
        
        // Calculate pages if not present (generic backend might not return it)
        if (data.pages === undefined && data.total !== undefined && data.page_size !== undefined) {
             data.pages = Math.ceil(data.total / data.page_size);
        }

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