import { db } from "@/lib/prisma";
import { UserRole } from "@prisma/client";
import { logger } from "@/lib/logger";
import { supabaseServer } from "@/lib/supabase/server";

export async function requireTeacher() {
  const supabase = await supabaseServer();
  if (!supabase) {
    return null;
  }

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return null; // Let the caller handle the redirect
  }

  const profile = await db.profile.findUnique({
    where: { id: user.id },
  }).catch((error) => {
    logger.error("Failed to load profile in requireTeacher", {
      userId: user.id,
      email: user.email,
      error: error instanceof Error ? error.message : "unknown",
    });
    return null;
  });

  if (
    !profile ||
    (profile.role !== UserRole.TEACHER && profile.role !== UserRole.SUPER_ADMIN)
  ) {
    logger.info("User authenticated but not authorized as teacher", {
      userId: user.id,
      email: user.email,
      role: profile?.role ?? "none",
    });
    return null;
  }

  return profile;
}
