import type { Metadata } from "next";
import Navbar from "./_components/navbar/Navbar";
import { redirect } from "next/navigation";
import { getServerSession } from "../api/auth/[...nextauth]/auth";
import { Error } from "_components/Error";
import { prisma } from "@repo/db";

export const metadata: Metadata = {
	title: "VAR: Pilot",
	description: "Die neue VAR Leitstelle.",
};

export default async function RootLayout({
	children,
}: Readonly<{
	children: React.ReactNode;
}>) {
	const session = await getServerSession();
	const openPenaltys = await prisma.penalty.findMany({
		where: {
			userId: session?.user.id,
			until: {
				gte: new Date(),
			},
			type: "TIME_BAN",
		},
	});

	if (!session || !session.user.firstname) {
		redirect("/login");
	}
	if (!session.user.emailVerified) {
		return <Error title="E-Mail-Adresse nicht verifiziert" statusCode={403} />;
	}

	if (!session.user.permissions.includes("PILOT"))
		return <Error title="Zugriff verweigert" statusCode={403} />;

	if (openPenaltys[0]) {
		return (
			<Error
				title="Du hast eine aktive Strafe"
				statusCode={403}
				description={`Du bist bis zum ${new Date(openPenaltys[0].until!).toLocaleString()} gesperrt.`}
			/>
		);
	}

	return (
		<>
			<Navbar />
			{children}
		</>
	);
}
