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

export const load: PageServerLoad = async ({ fetch, cookies, url, parent }) => {
    const parentData = await parent();
    const { accessToken } = getAuthTokens(cookies);

    if (!accessToken) {
        return {
            items: [],
            total: 0,
            page: 1,
            pageSize: 50,
            error: 'No authenticated'
        };
    }

    const search = url.searchParams.get('search') || '';
    const manifest_number = url.searchParams.get('manifest_number') || '';
    const start_date = url.searchParams.get('start_date') || '';
    const end_date = url.searchParams.get('end_date') || '';
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '50');
    const skip = (page - 1) * pageSize;

    const params = new URLSearchParams({
        skip: skip.toString(),
        limit: pageSize.toString()
    });

    if (search) params.append('search', search);
    if (manifest_number) params.append('manifest_number', manifest_number);
    if (start_date) params.append('start_date', start_date);
    if (end_date) params.append('end_date', end_date);

    try {
        const companyIdParam = url.searchParams.get('company_id') || url.searchParams.get('companyId');
        const cookieCompanyId = cookies.get('active_company_id');

        const companyId = companyIdParam
            ? companyIdParam
            : cookieCompanyId
                ? cookieCompanyId
                : parentData.companies?.[0]?.id?.toString();

        if (!companyId) {
            return {
                items: [],
                total: 0,
                page,
                pageSize,
                error: null
            };
        }

        params.append('company_id', companyId);

        const response = await authenticatedFetch(
            `v1/a76/manifests?${params.toString()}`,
            {},
            cookies,
            fetch,
            '/login'
        );

        if (!response.ok) {
            return {
                items: [],
                total: 0,
                page,
                pageSize,
                error: 'Error al cargar manifiestos'
            };
        }

        const data = await response.json();
        return {
            items: data.items || [],
            total: data.total || 0,
            page: data.page || page,
            pageSize: data.page_size || pageSize,
            error: null
        };
    } catch (error) {
        console.error('Error loading manifests:', error);
        return {
            items: [],
            total: 0,
            page,
            pageSize,
            error: 'Error al cargar manifiestos'
        };
    }
};
