import { redirect, render } from 'vike/abort';
import { getIdsBySlug } from '#/src/cache.js';
import { getRandomCampaigns } from '#/src/campaigns.js';
import { fetchScenesById } from '#/src/scenes.js';

function getTitle(scene) {
	if (scene.title) {
		return scene.title;
	}

	if (scene.actors.length > 0) {
		return `Scene with ${scene.actors.map((actor) => actor.name).join(', ')}`;
	}

	return 'Scene';
}

export async function onBeforeRender(pageContext) {
	if (pageContext._pageId === '/pages/scene/edit' && !pageContext.user) {
		throw redirect(`/login?r=${encodeURIComponent(pageContext.urlOriginal)}`);
	}

	const [scene] = await fetchScenesById([Number(pageContext.routeParams.sceneId)], {
		reqUser: pageContext.user,
		includeAssets: true,
		includePartOf: true,
		actorStashes: true,
		restriction: pageContext.geo.restriction,
	});

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

	const [campaigns, tagIds] = await Promise.all([
		getRandomCampaigns([
			{
				minRatio: 1.5,
				entityIds: [scene.channel.id, scene.network?.id].filter(Boolean),
				allowRandomFallback: false,
			},
		], { tagFilter: pageContext.tagFilter }),
		getIdsBySlug([
			'anal',
			'creampie',
			'dp',
			'facial',
		], 'tags', true),
	]);

	return {
		pageContext: {
			title: getTitle(scene),
			pageProps: {
				scene,
				tagIds,
			},
			campaigns: {
				scene: campaigns[0],
			},
		},
	};
}
