import { redirect, render } from 'vike/abort';

import { fetchActorsById } from '#/src/actors.js';
import { getCampaignIndex, getRandomCampaigns } from '#/src/campaigns.js';
import { fetchCountries } from '#/src/countries.js';
import { fetchMovies } from '#/src/movies.js';
import { fetchScenes } from '#/src/scenes.js';
import { curateMoviesQuery } from '#/src/web/movies.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

async function fetchReleases(pageContext) {
	if (pageContext.routeParams.domain === 'movies') {
		return fetchMovies(await curateMoviesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			actorId: Number(pageContext.routeParams.actorId),
			tagFilter: pageContext.tagFilter,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}, pageContext.user);
	}

	return fetchScenes(await curateScenesQuery({
		...pageContext.urlQuery,
		scope: pageContext.routeParams.scope || 'latest',
		actorId: Number(pageContext.routeParams.actorId),
		tagFilter: pageContext.tagFilter,
	}), {
		page: Number(pageContext.routeParams.page) || 1,
		limit: Number(pageContext.urlParsed.search.limit) || 30,
		aggregate: true,
	}, pageContext.user);
}

export async function onBeforeRender(pageContext) {
	const isEditing = pageContext._pageId === '/pages/actors/@actorId/edit';

	if (isEditing && !pageContext.user) {
		throw redirect(`/login?r=${encodeURIComponent(pageContext.urlOriginal)}`);
	}

	console.time('page fetch actor');
	const [actor] = await fetchActorsById([Number(pageContext.routeParams.actorId)], {}, pageContext.user);
	console.timeEnd('page fetch actor');

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

	console.time('page fetch actor assets');
	const [actorReleases, campaigns, countries] = await Promise.all([
		fetchReleases(pageContext),
		getRandomCampaigns([
			// don't show meta campaign, too intrusive under actor bio
			{ minRatio: 3 },
			pageContext.routeParams.domain === 'scenes'
				? { minRatio: 0.75, maxRatio: 1.25 }
				: null,
		].filter(Boolean), { tagFilter: pageContext.tagFilter }),
		isEditing && fetchCountries(),
	]);
	console.timeEnd('page fetch actor assets');

	if (actor.alias && actorReleases.scenes.length === 0 && !Object.hasOwn(pageContext.urlParsed.search, 'inspect')) {
		throw redirect(`/actor/${actor.alias.id}/${actor.alias.slug}`);
	}

	const campaignIndex = getCampaignIndex(actorReleases.limit);
	const [paginationCampaign, sceneCampaign] = campaigns;

	return {
		pageContext: {
			title: isEditing
				? `Editing '${actor.name}'`
				: actor.name,
			pageProps: {
				actor,
				countries,
				...actorReleases,
			},
			campaigns: {
				index: campaignIndex,
				scenes: actorReleases.limit > 5 && sceneCampaign,
				pagination: paginationCampaign,
			},
		},
	};
}
