import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth/requireUser";

const readTeacherEmails = (): string[] =>
  (process.env.TEACHER_EMAILS ?? "")
    .split(",")
    .map((email) => email.trim().toLowerCase())
    .filter(Boolean);

export const requireTeacher = async () => {
  const user = await requireUser("/teacher");
  if (!user?.email) {
    redirect("/");
  }

  const allowed = readTeacherEmails();
  if (allowed.length === 0) {
    redirect("/");
  }

  if (!allowed.includes(user.email.toLowerCase())) {
    redirect("/");
  }

  return user;
};
