import { redirect } from 'vike/abort';

import { fetchActorsById } from '#/src/actors.js';
import { fetchCountries } from '#/src/countries.js';

export async function onBeforeRender(pageContext) {
	if (!pageContext.user) {
		throw redirect(`/login?r=${encodeURIComponent(pageContext.urlOriginal)}`);
	}

	const [actor] = pageContext.routeParams.actorId
		? await fetchActorsById([Number(pageContext.routeParams.actorId)], {}, pageContext.user)
		: [];

	const countries = await fetchCountries();

	/*
	if (!actor) {
		throw render(404, `Cannot find actor '${pageContext.routeParams.actorId}'.`);
	}
	*/

	return {
		pageContext: {
			title: actor
				? `Editing '${actor.name}'`
				: 'Adding actor',
			pageProps: {
				actor,
				countries,
			},
		},
	};
}
