import type { Metadata } from "next";
import localFont from "next/font/local";
import "./globals.css";
import { NextAuthSessionProvider } from "./_components/AuthSessionProvider";
import { getServerSession } from "./api/auth/[...nextauth]/auth";
import { Toaster } from "react-hot-toast";
import { QueryProvider } from "_components/QueryProvider";
import { prisma } from "@repo/db";
import { Error as ErrorComp } from "_components/Error";
import { Maintenance } from "@repo/shared-components";

const geistSans = localFont({
	src: "./fonts/GeistVF.woff",
	variable: "--font-geist-sans",
});
const geistMono = localFont({
	src: "./fonts/GeistMonoVF.woff",
	variable: "--font-geist-mono",
});

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

export default async function RootLayout({
	children,
}: Readonly<{
	children: React.ReactNode;
}>) {
	const session = await getServerSession();

	const config = await prisma.config.findFirst({
		orderBy: [{ createdAt: "desc" }],
	});

	return (
		<html lang="de" data-theme="dark">
			<body
				className={`${geistSans.variable} ${geistMono.variable} h-screen flex flex-col overflow-hidden`}
			>
				<QueryProvider>
					<NextAuthSessionProvider session={session}>
						<Toaster
							containerStyle={{
								top: 80,
								left: 50,
							}}
							toastOptions={{
								style: {
									background: "var(--color-base-100)",
									color: "var(--color-base-content)",
									zIndex: 9999,
								},
								duration: 5000,
							}}
							position="top-left"
							reverseOrder={false}
						/>
						{session?.user.isBanned && (
							<ErrorComp title="You are banned from using this service" statusCode={403} />
						)}
						{config?.maintenanceEnabled && !session?.user.permissions.includes("ADMIN_MESSAGE") && (
							<Maintenance message={config?.message} />
						)}
						{!session?.user.isBanned &&
							(!config?.maintenanceEnabled ||
								session?.user.permissions.includes("ADMIN_MESSAGE")) &&
							children}
					</NextAuthSessionProvider>
				</QueryProvider>
			</body>
		</html>
	);
}
