import { error, redirect } from '@sveltejs/kit';
import { createApiClient } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';

export async function load({ fetch }) {
	const api = createApiClient(fetch);
	const result = await api.GET('/api/network');

	if (result.response.status === 401) throw redirect(302, '/login');

	if (!result.response.ok) {
		const code = (result.error as unknown as { code?: string })?.code;
		throw error(result.response.status, getErrorMessage(code));
	}

	const network = result.data!;
	return { nodes: network.nodes ?? [], edges: network.edges ?? [] };
}
