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) {
            let errorMessage = `Error: ${response.status} ${response.statusText}`;
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                // Not a JSON error or other issue
            }
            return {
                ports: { items: [], total: 0, page, page_size: pageSize, pages: 0 },
                error: errorMessage,
                status: response.status
            };
        }

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