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);

    const pUser = parentData.user as
        | { preferred_username?: string; name?: string; email?: string }
        | undefined
        | null;
    const defaultLastUser =
        (pUser?.preferred_username?.trim() || pUser?.name?.trim() || pUser?.email?.trim() || '') || '';

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

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

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

        if (integrationNumber) filters.integration_number = integrationNumber;

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

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

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