import { render } from 'vike/abort';

import { emailTemplates, listEmailTemplates } from '#/src/email-templates.js';

export default async function onBeforeRender(pageContext) {
	if (!pageContext.user || pageContext.user.role === 'user') {
		throw render(404);
	}

	const { template } = pageContext.routeParams;

	if (!listEmailTemplates().includes(template)) {
		throw render(404);
	}

	let html = null;
	let text = null;
	let error = null;

	try {
		({ html, text } = await emailTemplates.render(`${template}.vue`));
	}
	catch (renderError) {
		error = renderError.message;
	}

	return {
		pageContext: {
			title: `E-mail Preview: ${template}`,
			pageProps: {
				template,
				html,
				text,
				error,
			},
		},
	};
}
