import { getServerApiUrl, getAuthTokens } from '$lib/server/api';
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
    const parentData = await parent();
    const { accessToken } = getAuthTokens(cookies);
    if (!accessToken) {
        throw redirect(302, '/login');
    }

    const page = Number(url.searchParams.get('page')) || 1;
    const pageSize = Number(url.searchParams.get('page_size')) || 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 {
            items: [],
            total: 0,
            page,
            pageSize,
            pages: 0,
            error: 'Selecciona una compañía para ver los puertos'
        };
    }

    const apiUrl = getServerApiUrl();
    const query = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString()
    });

    const endpoint = `${apiUrl}v1/a76/ports?${query.toString()}`;

    try {
        const response = await fetch(endpoint, {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });

        if (!response.ok) {
            console.error(`Error fetching ports: ${response.status} ${response.statusText}`);
            return {
                items: [],
                total: 0,
                page,
                pageSize,
                pages: 0,
                error: `Error: ${response.statusText}`
            };
        }

        const data = await response.json();
        return {
            items: data.items,
            total: data.total,
            page: data.page,
            pageSize: data.page_size,
            pages: data.pages
        };
    } catch (error) {
        console.error('Error fetching ports:', error);
        return {
            items: [],
            total: 0,
            page,
            pageSize,
            pages: 0,
            error: 'Failed to connect to server'
        };
    }
};
