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

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

        if (notice_number) filters.notice_number = notice_number;
        if (pedimento) filters.pedimento = pedimento;

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

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

        const noticesData = await response.json();
        // Calculate pages if not present
        if (noticesData.pages === undefined && noticesData.total !== undefined && noticesData.page_size !== undefined) {
             noticesData.pages = Math.ceil(noticesData.total / noticesData.page_size);
        }

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