import { fetchScenes } from '#/src/scenes.js';
import { curateScenesQuery } from '#/src/web/scenes.js';
import { getRandomCampaigns, getCampaignIndex } from '#/src/campaigns.js';

export async function onBeforeRender(pageContext) {
	const withQuery = Object.hasOwn(pageContext.urlParsed.search, 'q');

	const [
		sceneResults,
		campaigns,
	] = await Promise.all([
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			isShowcased: withQuery ? null : true,
			tagFilter: pageContext.tagFilter,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 29,
			aggregate: withQuery,
		}, pageContext.user),
		getRandomCampaigns([
			{ minRatio: 1.5 },
			{ minRatio: 0.75, maxRatio: 1.25 },
			{ minRatio: 1.5 },
		], { tagFilter: pageContext.tagFilter }),
	]);

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

	const campaignIndex = getCampaignIndex(scenes.length);
	const [scopeCampaign, sceneCampaign, paginationCampaign] = campaigns;

	return {
		pageContext: {
			title: pageContext.routeParams.scope,
			pageProps: {
				scenes,
				aggTags,
				aggChannels,
				aggActors,
				limit,
				total,
			},
			campaigns: {
				index: campaignIndex,
				scope: scopeCampaign,
				scenes: scenes.length > 5 && sceneCampaign,
				pagination: paginationCampaign,
			},
		},
	};
}