import { Geist, Geist_Mono } from "next/font/google";
import { NextAuthSessionProvider } from "./_components/AuthSessionProvider";
import { getServerSession } from "./api/auth/[...nextauth]/auth";
import { CustomErrorBoundary } from "_components/ErrorBoundary";
import { Toaster } from "react-hot-toast";
import "./globals.css";
import { QueryProvider } from "_components/QueryClient";
import { prisma } from "@repo/db";
import React from "react";
import { Error as ErrorComp } from "_components/Error";
import { Maintenance } from "@repo/shared-components";

const geistSans = Geist({
	variable: "--font-geist-sans",
	subsets: ["latin"],
});

const geistMono = Geist_Mono({
	variable: "--font-geist-mono",
	subsets: ["latin"],
});

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

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

	return (
		<html lang="en" data-theme="dark">
			<NextAuthSessionProvider session={session}>
				<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
					{latestNotam?.maintenanceEnabled &&
						!session?.user.permissions.includes("ADMIN_MESSAGE") && (
							<Maintenance message={latestNotam?.message} />
						)}
					{(!latestNotam?.maintenanceEnabled ||
						session?.user.permissions.includes("ADMIN_MESSAGE")) && (
						<>
							<div>
								<Toaster
									containerStyle={{ zIndex: "999999999" }}
									position="top-center"
									reverseOrder={false}
								/>
							</div>
							<QueryProvider>
								<CustomErrorBoundary>{children}</CustomErrorBoundary>
							</QueryProvider>
						</>
					)}
				</body>
			</NextAuthSessionProvider>
		</html>
	);
};

RootLayout.displayName = "RootLayout";

export default RootLayout;
