import { render } from 'vike/abort';

import { HttpError } from '#/src/errors.js';
import { fetchMovies } from '#/src/movies.js';
import { fetchStashByUsernameAndSlug } from '#/src/stashes.js';
import { curateMoviesQuery } from '#/src/web/movies.js';

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

		const movieResults = await fetchMovies(await curateMoviesQuery({
			...pageContext.urlQuery,
			scope: pageContext.routeParams.scope || 'latest',
			stashId: stash.id,
			tagFilter: pageContext.tagFilter,
		}), {
			page: Number(pageContext.routeParams.page) || 1,
			limit: Number(pageContext.urlParsed.search.limit) || 50,
		}, pageContext.user);

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

		throw error;
	}
}
