import markdownItClass from '@toycode/markdown-it-class';
import markdownIt from 'markdown-it';
import { redirect } from 'vike/abort';

import { getCampaignIndex, getRandomCampaigns } from '#/src/campaigns.js';
import { fetchMovies } from '#/src/movies.js';
import { fetchScenes } from '#/src/scenes.js';
import { fetchTagsById } from '#/src/tags.js';
import { curateMoviesQuery } from '#/src/web/movies.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

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

async function fetchReleases(pageContext) {
	if (pageContext.routeParams.domain === 'movies') {
		return fetchMovies(await curateMoviesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			tagSlug: pageContext.routeParams.tagSlug,
			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',
		tagSlug: pageContext.routeParams.tagSlug,
		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 tagSlug = pageContext.routeParams.tagSlug;
	const [tag] = await fetchTagsById([tagSlug], {}, pageContext.user, { restriction: pageContext.geo.restriction });

	if (tag.aliasFor) {
		throw redirect(`/tag/${tag.aliasFor}`);
	}

	const [tagReleases, campaigns] = await Promise.all([
		fetchReleases(pageContext),
		getRandomCampaigns([
			{ tagSlugs: [tagSlug], minRatio: 0.75, maxRatio: 1.25 },
			{ tagSlugs: [tagSlug], minRatio: 3 },
			{ tagSlugs: [tagSlug], minRatio: 3 },
			pageContext.routeParams.domain === 'scenes'
				? { tagSlugs: [tagSlug], minRatio: 0.75, maxRatio: 1.25 }
				: null,
		].filter(Boolean), { tagFilter: pageContext.tagFilter }),
	]);

	const releases = tagReleases.scenes || tagReleases.movies;
	const description = tag.description && md.renderInline(tag.description);

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

	return {
		pageContext: {
			title: tag.name,
			pageProps: {
				tag,
				description,
				...tagReleases,
			},
			campaigns: {
				index: campaignIndex,
				photos: photosCampaign,
				meta: metaCampaign,
				scenes: releases.length > 5 && sceneCampaign,
				pagination: paginationCampaign,
			},
		},
	};
}
