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

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

	const {
		scenes,
	} = sceneResults;

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

	return {
		pageContext: {
			title: pageContext.routeParams.scope,
			pageProps: {
				...sceneResults,
			},
			campaigns: {
				index: campaignIndex,
				scenes: scenes.length > 5 && sceneCampaign,
				pagination: paginationCampaign,
			},
		},
	};
}
