import markdownIt from 'markdown-it';
import markdownItClass from '@toycode/markdown-it-class';

import { fetchTagsById } from '#/src/tags.js';
import { fetchScenes } from '#/src/scenes.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

const md = markdownIt().use(markdownItClass, { a: 'link' });

export async function onBeforeRender(pageContext) {
	const [[tag], tagScenes] = await Promise.all([
		fetchTagsById([pageContext.routeParams.tagSlug]),
		fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			tagSlug: pageContext.routeParams.tagSlug,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
			aggregate: true,
		}),
	]);

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

	const description = tag.description && md.renderInline(tag.description);

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