import { fetchActors } from '#/src/actors.js';
import { fetchEntities } from '#/src/entities.js';
import { fetchMovies } from '#/src/movies.js';
import { fetchScenes } from '#/src/scenes.js';
import { curateActorsQuery } from '#/src/web/actors.js';
import { curateMoviesQuery } from '#/src/web/movies.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

export async function onBeforeRender(pageContext) {
	const [searchScenes, searchActors, searchMovies, entities] = await Promise.all([
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			query: pageContext.urlParsed.search.q,
			scope: pageContext.urlParsed.search.scope || 'results',
			tagFilter: pageContext.tagFilter,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 15,
		}, pageContext.user, { restriction: pageContext.geo.restriction }),
		fetchActors(curateActorsQuery(pageContext.urlQuery), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 10,
			order: ['results', 'desc'],
		}, pageContext.user, { restriction: pageContext.geo.restriction }),
		fetchMovies(await curateMoviesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'results',
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 5,
		}, pageContext.user, { restriction: pageContext.geo.restriction }),
		fetchEntities({
			query: pageContext.urlParsed.search.q,
			limit: 5,
		}, {
			restriction: pageContext.geo.restriction,
		}),
	]);

	const {
		scenes,
		aggYears,
		aggActors,
		aggTags,
		aggChannels,
		total: sceneTotal,
	} = searchScenes;

	const {
		actors,
		total: actorTotal,
	} = searchActors;

	const {
		movies,
		total: movieTotal,
	} = searchMovies;

	return {
		pageContext: {
			title: `Search '${pageContext.urlParsed.search.q || ''}'`,
			pageProps: {
				actors,
				scenes,
				movies,
				entities,
				aggYears,
				aggActors,
				aggTags,
				aggChannels,
				sceneTotal,
				actorTotal,
				movieTotal,
			},
		},
	};
}
