import { render } from 'vike/abort';

import { HttpError } from '#/src/errors.js';
import { fetchScenes } from '#/src/scenes.js';
import { fetchStashByUsernameAndSlug } from '#/src/stashes.js';
import { curateScenesQuery } from '#/src/web/scenes.js';

export async function onBeforeRender(pageContext) {
	try {
		const stash = await fetchStashByUsernameAndSlug(pageContext.routeParams.username, pageContext.routeParams.stashSlug, pageContext.user);

		const stashScenes = await fetchScenes(await curateScenesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'stashed',
			stashId: stash.id,
			tagFilter: pageContext.tagFilter,
			isShowcased: null,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 30,
		}, pageContext.user);

		return {
			pageContext: {
				title: `${stash.name} by ${stash.user.username}`,
				pageProps: {
					stash,
					...stashScenes,
				},
			},
		};
	}
	catch (error) {
		if (error instanceof HttpError) {
			throw render(error.httpCode, error.message);
		}

		throw error;
	}
}
