import { render } from 'vike/abort';

import { fetchScenes } from '#/src/scenes.js';
import { fetchSeriesById } from '#/src/series.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

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

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

	return 'Serie';
}

export async function onBeforeRender(pageContext) {
	const [[serie], serieScenes] = await Promise.all([
		fetchSeriesById([Number(pageContext.routeParams.serieId)], pageContext.user),
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: 'oldest',
			serieId: Number(pageContext.routeParams.serieId),
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}, pageContext.user),
	]);

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

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

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