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 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,
			dedupe: true,
		}, pageContext.user, { restriction: pageContext.restriction }),
		getRandomCampaigns([
			{ minRatio: 2.0, maxRatio: 5 },
			{ minRatio: 0.75, maxRatio: 1.25 },
			{ minRatio: 1.5 },
		], { tagFilter: pageContext.tagFilter }),
	]);

	const {
		scenes,
	} = sceneResults;

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

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