import { COOKIE_NAME } from "$lib/constants";
import { getUserFromSession } from "$lib/database";

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
	//if (event.url.pathname !== "/maintenance" && process.env.MAINTENANCE) {
	//	return new Response("", { status: 302, headers: { Location: "/maintenance" } });
	//}

	const cookie = event.cookies.get(COOKIE_NAME);
	if (!cookie) {
		if (event.routeId.startsWith("(app)")) return new Response("", { status: 302, headers: { Location: "/landing" } });
		return await resolve(event);
	}

	let user = await getUserFromSession(cookie, event.request.headers.get("x-forwarded-for") || event.getClientAddress());
	if (!user) {
		event.cookies.delete(COOKIE_NAME, { secure: !!process.env.PRODUCTION });
		if (event.routeId.startsWith("(app)")) return new Response("", { status: 302, headers: { Location: "/landing" } });
	} else
		event.locals.user = {
			_id: user._id,
			username: user.username,
			currency: user.currency,
			thumbnails: {
				headshot: "/img/headshot.png",
				bodyshot: "https://media.tenor.com/Lo0GvkoTFR4AAAAd/xbox-xbox-avatar.gif"
			}
		};

	return await resolve(event);
}
