import { render } from 'vike/abort';

import { fetchMoviesById } from '#/src/movies.js';
import { fetchScenes } from '#/src/scenes.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

function getTitle(movie) {
	if (movie.title) {
		return movie.title;
	}

	if (movie.actors.length > 0) {
		return `Movie with ${movie.actors.map((actor) => actor.name).join(', ')}`;
	}

	return 'Movie';
}

export async function onBeforeRender(pageContext) {
	const [[movie], movieScenes] = await Promise.all([
		fetchMoviesById([Number(pageContext.routeParams.movieId)], pageContext.user, { restriction: pageContext.geo.restriction }),
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: 'oldest',
			movieId: Number(pageContext.routeParams.movieId),
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}, pageContext.user, {
			restriction: pageContext.geo.restriction,
		}),
	]);

	if (!movie) {
		throw render(404, `Cannot find movie '${pageContext.routeParams.movieId}'.`);
	}

	const {
		scenes,
		aggActors,
		aggTags,
		aggChannels,
		total,
		limit,
	} = movieScenes;

	return {
		pageContext: {
			title: getTitle(movie),
			pageProps: {
				movie,
				scenes,
				aggActors,
				aggTags,
				aggChannels,
				total,
				limit,
			},
		},
	};
}
