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

export const dynamic = "force-dynamic";

export default async function AssignPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const establishmentId = session.user.establishmentId;
  const templates = await prisma.template.findMany({
    where: { OR: [{ isPublic: true }, ...(establishmentId ? [{ establishmentId }] : [])] },
    orderBy: { createdAt: "desc" },
  });

  const nodes = await prisma.node.findMany({
    where: establishmentId
      ? { student: { class: { establishmentId } } }
      : {},
    include: { student: { include: { class: true } } },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div className="space-y-6 max-w-xl">
      <h1 className="text-3xl font-bold">Attribuer une instance</h1>
      <AssignForm templates={templates} nodes={nodes} />
    </div>
  );
}
