import config from 'config';
import { renderPage } from 'vike/server';

import { socials } from '../../common/actors.mjs';
import pkg from '../../package.json' with { type: 'json' };
import { fetchUnseenNotificationsCount } from '../alerts.js';
import { fetchUserStashes } from '../stashes.js';
import { fetchUserTemplates } from '../users.js';

export default async function mainHandler(req, res, next) {
	const [stashes, templates, unseenNotifications] = req.user
		? await Promise.all([
				fetchUserStashes(req.user.id, req.user),
				fetchUserTemplates(req.user),
				fetchUnseenNotificationsCount(req.user),
			])
		: [];

	const pageContextInit = {
		urlOriginal: req.originalUrl,
		urlQuery: req.query, // vike's own query does not apply boolean parser
		headers: req.headers,
		cookies: req.cookies,
		tagFilter: req.tagFilter,
		user: req.user && {
			id: req.user.id,
			username: req.user.username,
			email: req.user.email,
			settings: req.user.settings,
			role: req.user.role,
			abilities: req.user.abilities,
			avatar: req.user.avatar,
			isEmailVerified: req.user.isEmailVerified,
		},
		assets: req.user
			? {
					stashes,
					primaryStash: stashes.find((stash) => stash.isPrimary),
					templates,
					unseenNotifications,
				}
			: null,
		env: {
			version: pkg.version,
			theme: req.cookies.theme || req.headers['sec-ch-prefers-color-scheme'] || 'light',
			scenesView: req.cookies.scenesView || 'list',
			selectedTemplate: Number(req.cookies.selectedTemplate) || 0,
			allowLogin: config.auth.login,
			allowSignup: config.auth.signup,
			maxMatches: config.database.manticore.maxMatches,
			maxAggregateSize: config.database.manticore.maxAggregateSize,
			origin: config.origin,
			media: config.media,
			psa: config.psa,
			links: config.links,
			socials,
			emailEnabled: config.email.enabled,
			captcha: {
				enabled: config.auth.captcha.enabled,
				siteKey: config.auth.captcha.siteKey,
			},
		},
		geo: req.geo,
		meta: {
			now: new Date().toISOString(),
		},
	};

	const pageContext = await renderPage(pageContextInit);
	const { httpResponse } = pageContext;

	if (pageContext.errorWhileRendering) {
		console.error(pageContext.errorWhileRendering);
	}

	if (!httpResponse) {
		next();
		return;
	}

	/*
	if (res.writeEarlyHints) {
		res.writeEarlyHints({ link: httpResponse.earlyHints.map((e) => e.earlyHintLink) });
	}
	*/

	httpResponse.headers.forEach(([name, value]) => res.setHeader(name, value));
	res.status(httpResponse.statusCode);
	// For HTTP streams use httpResponse.pipe() instead, see https://vike.dev/stream
	res.send(httpResponse.body);
}
