import { render } from 'vike/abort';

import { fetchActorRevisions } from '#/src/actors.js';
import { fetchAlerts } from '#/src/alerts.js';
import { fetchUserKeys } from '#/src/auth.js';
import { fetchSceneRevisions } from '#/src/scenes.js';
import { fetchUserStashes } from '#/src/stashes.js';
import { fetchUser } from '#/src/users.js';

async function fetchRevisions(pageContext) {
	if (pageContext.routeParams.username !== pageContext.user?.username) {
		return {};
	}

	if (pageContext.routeParams.section === 'revisions' && pageContext.routeParams.domain === 'scenes') {
		return fetchSceneRevisions(null, {
			userId: pageContext.user.id,
			limit: 100,
		}, pageContext.user);
	}

	if (pageContext.routeParams.section === 'revisions' && pageContext.routeParams.domain === 'actors') {
		return fetchActorRevisions(null, {
			userId: pageContext.user.id,
			limit: 100,
		}, pageContext.user);
	}

	return {};
}

export async function onBeforeRender(pageContext) {
	const [profile, alerts, userRevisions, keys] = await Promise.all([
		fetchUser(pageContext.routeParams.username, { throwError: false }, pageContext.user),
		pageContext.routeParams.section === 'alerts' && pageContext.routeParams.username === pageContext.user?.username
			? fetchAlerts(pageContext.user)
			: [],
		fetchRevisions(pageContext),
		pageContext.routeParams.section === 'api'
			? fetchUserKeys(pageContext.user)
			: [],
	]);

	if (!profile) {
		throw render(404, `Cannot find user '${pageContext.routeParams.username}'.`);
	}

	const {
		revisions,
		actors,
		tags,
		movies,
		avatars,
	} = userRevisions;

	const stashes = await fetchUserStashes(profile.id, pageContext.user);

	return {
		pageContext: {
			title: profile.username,
			pageProps: {
				profile, // differentiate from authed 'user'
				stashes,
				alerts,
				revisions,
				keys,
				actors,
				tags,
				movies,
				avatars,
			},
		},
	};
}
