import { render } from 'vike/abort';

import redis from '#/src//redis.js';
import { getCampaignIndex, getRandomCampaigns } from '#/src/campaigns.js';
import entityPrefixes from '#/src/entities-prefixes.js';
import { fetchEntitiesById } from '#/src/entities.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, entityId) {
	if (pageContext.routeParams.domain === 'movies') {
		return fetchMovies(await curateMoviesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			entityId: Number(entityId),
			tagFilter: pageContext.tagFilter,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}, pageContext.user, {
			restriction: pageContext.geo.restriction,
		});
	}

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

export async function onBeforeRender(pageContext) {
	// const entityId = await redis.hGet('traxxx:entities:id_by_slug', pageContext.routeParams.entityType === 'network' ? `_${pageContext.routeParams.entitySlug}` : pageContext.routeParams.entitySlug);
	const entityId = await redis.hGet('traxxx:entities:id_by_slug', `${entityPrefixes[pageContext.routeParams.entityType]}${pageContext.routeParams.entitySlug}`);

	if (!entityId) {
		throw render(404, `Cannot find ${pageContext.routeParams.entityType} '${pageContext.routeParams.entitySlug}'.`);
	}

	const [
		[entity],
		entityReleases,
	] = await Promise.all([
		fetchEntitiesById([Number(entityId)], { includeChildren: true }, pageContext.user, {
			restriction: pageContext.geo.restriction,
		}),
		fetchReleases(pageContext, entityId),
	]);

	const entityIds = entity.isIndependent || !entity.parent
		? [entity.id]
		: [entity.id, entity.parent.id];

	const campaigns = await getRandomCampaigns([
		{
			entityIds,
			minRatio: 3,
			allowRandomFallback: false,
		},
		{
			entityIds,
			minRatio: 3,
			allowRandomFallback: false,
		},
		pageContext.routeParams.domain === 'scenes'
			? {
					entityIds,
					minRatio: 0.75,
					maxRatio: 1.25,
					allowRandomFallback: false,
				}
			: null,
	].filter(Boolean), { tagFilter: pageContext.tagFilter });

	const releases = entityReleases.scenes || entityReleases.movies;

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

	return {
		pageContext: {
			title: entity.name,
			pageProps: {
				entity,
				...entityReleases,
			},
			campaigns: {
				index: campaignIndex,
				meta: metaCampaign,
				scenes: releases.length > 5 && sceneCampaign,
				pagination: paginationCampaign,
			},
		},
	};
}
