import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { AdminSidebar } from "@/components/admin/AdminSidebar";
import { prisma } from "@/lib/db";

export const metadata: Metadata = {
  title: { default: "Admin Panel", template: "%s — Admin" },
  robots: { index: false, follow: false },
};

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  const session = await getSession();

  // Login page is exempt
  return (
    <div dir="rtl" className="min-h-screen bg-background font-persian">
      {session.isLoggedIn ? (
        <AuthedLayout username={session.username}>{children}</AuthedLayout>
      ) : (
        children
      )}
    </div>
  );
}

async function AuthedLayout({
  children,
  username,
}: {
  children: React.ReactNode;
  username?: string;
}) {
  const unreadCount = await prisma.contactMessage.count({ where: { isRead: false } });

  return (
    <>
      <AdminSidebar username={username} unreadCount={unreadCount} />
      <main className="lg:pr-64 min-h-screen">
        <div className="p-6 lg:p-8">{children}</div>
      </main>
    </>
  );
}
