import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import NewUserForm from "./NewUserForm";

export const dynamic = "force-dynamic";

export default async function NewUserPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");

  const isSuperadmin = session.user.role === "superadmin";
  if (!isSuperadmin && session.user.role !== "admin") redirect("/dashboard");

  const establishments = isSuperadmin
    ? await prisma.establishment.findMany({ orderBy: { name: "asc" } })
    : [];

  return (
    <div className="space-y-6 max-w-xl">
      <h1 className="text-3xl font-bold">Nouvel utilisateur</h1>
      <NewUserForm establishments={establishments} isSuperadmin={isSuperadmin} />
    </div>
  );
}
