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

export const load: PageServerLoad = async ({ params, cookies, fetch }) => {
	const { accessToken } = getAuthTokens(cookies);

	if (!accessToken) {
		throw redirect(302, '/login');
	}

	const companyId = await getActiveCompanyId(cookies, fetch);
	if (!companyId) {
		throw error(400, 'No se encontró una compañía seleccionada');
	}

	let agentsCount = 0;
	let clientsCount = 0;

	try {
		const [brokersRes, clientsRes] = await Promise.all([
			authenticatedFetch(
				`v1/a76/customs-brokers?company_id=${companyId}&page=1&page_size=1`,
				{},
				cookies,
				fetch
			),
			authenticatedFetch(
				`v1/a76/clients-providers?company_id=${companyId}&page=1&page_size=1`,
				{},
				cookies,
				fetch
			)
		]);

		if (brokersRes.ok) {
			const brokersData = await brokersRes.json();
			agentsCount = brokersData.total ?? 0;
		}
		if (clientsRes.ok) {
			const clientsData = await clientsRes.json();
			clientsCount = clientsData.total ?? 0;
		}
	} catch (e) {
		console.error('Error fetching prerequisites count for parts:', e);
	}

	const isCreate = params.id === 'new' || params.id === undefined;

	return {
		agentsCount,
		clientsCount,
		isCreate
	};
};
