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

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
    await parent();
    const { accessToken } = getAuthTokens(cookies);
    
    if (!accessToken) {
        return { error: 'No authenticated', customs_units: { 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 code = url.searchParams.get('code');
        const description = url.searchParams.get('description');

        if (code) filters.code = code;
        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;

        const queryParams = new URLSearchParams({ 
            company_id: companyId.toString(),
            page: page.toString(), 
            page_size: pageSize.toString(), 
            ...filters 
        });
        const response = await authenticatedFetch(`v1/a76/units-of-measure/customs/?${queryParams.toString()}`, { method: 'GET' }, cookies, fetch);
    
        if (!response.ok) {
            let errorMessage = 'Failed to load';
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                // Silently fail if not JSON
            }
            return { error: errorMessage, status: response.status, customs_units: { items: [], total: 0, page, page_size: pageSize, pages: 0 } };
        }

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