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

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
    // Esperar a que el layout padre valide/refresque el token
    const parentData = await parent();

    const { accessToken } = getAuthTokens(cookies);

    if (!accessToken) {
        return {
            error: 'No authenticated',
            companies: {
                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 name = url.searchParams.get('name');
        const rfc = url.searchParams.get('rfc');

        if (name) filters.name = name;
        if (rfc) filters.rfc = rfc; 

        // Construir URL con parámetros
        const queryParams = new URLSearchParams({
            page: page.toString(),
            page_size: pageSize.toString(),
            ...filters
        });

        const response = await authenticatedFetch(
            `v1/a76/company?${queryParams.toString()}`,
            { method: 'GET' },
            cookies,
            fetch
        );

        if (!response.ok) {
            let errorMsg = 'Failed to load companies';
            try {
                const errorData = await response.json();
                errorMsg = errorData.detail || errorData.message || errorMsg;
            } catch (e) {
                // Ignore
            }
            return {
                error: errorMsg,
                status: response.status,
                companies: {
                    items: [],
                    total: 0,
                    page: page,
                    page_size: pageSize,
                    pages: 0
                }
            };
        }

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