import { render } from 'vike/abort'; /* eslint-disable-line import/extensions */

import { fetchEntitiesById } from '#/src/entities.js';
import { fetchScenes } from '#/src/scenes.js';
import { curateScenesQuery } from '#/src/web/scenes.js';
import redis from '#/src//redis.js';

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);

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

	const [[entity], entityScenes] = await Promise.all([
		fetchEntitiesById([Number(entityId)], { includeChildren: true }),
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			entityId: Number(entityId),
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}),
	]);

	const {
		scenes,
		aggActors,
		aggTags,
		aggChannels,
		total,
		limit,
	} = entityScenes;

	return {
		pageContext: {
			title: entity.name,
			pageProps: {
				entity,
				scenes,
				aggActors,
				aggTags,
				aggChannels,
				total,
				limit,
			},
		},
	};
}
