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

    const page = Number(url.searchParams.get('page')) || 1;
    const pageSize = Number(url.searchParams.get('page_size')) || 50;

    const cookieCompanyId = cookies.get('active_company_id');
    const companyId = cookieCompanyId
        ? parseInt(cookieCompanyId)
        : parentData.companies?.[0]?.id;

    if (!companyId) {
        return {
            error: 'No company selected',
            locations: { items: [], total: 0, page, page_size: pageSize, pages: 0 }
        };
    }

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

    if (location_code) filters.location_code = location_code;
    if (location_description) filters.location_description = location_description;
    
    try {
        const queryParams = new URLSearchParams({
            page: page.toString(),
            page_size: pageSize.toString(),
            company_id: companyId.toString(),
            ...filters
        });

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

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

        const data = await response.json();
        
        return { locations: data };
    } catch (error) {
        console.error('Error loading locations:', error);
        return {
            error: 'Error loading',
            locations: { items: [], total: 0, page: 1, page_size: pageSize, pages: 0 }
        };
    }
};
