import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";
import { db } from "@/lib/prisma";
import { UserRole } from "@prisma/client";
import { logger } from "@/lib/logger";

export async function requireTeacher() {

  const cookieStore = await cookies();

  // 1. Get Supabase Session
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() { return cookieStore.getAll() },
        setAll(cookiesToSet: { name: string; value: string; options?: CookieOptions }[]) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch (error) {
            // This is expected in Server Components, but let's log it just in case
            logger.warn("Failed to set cookies in Server Component context (expected behavior)", error);
          }
        },
      },
    }
  );

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

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

  // 2. Check Role in Database
  const profile = await db.profile.findUnique({
    where: { id: user.id },
  }
  );
  console.log("AUTH_USER_ID:", user.id);
  console.log("DB_PROFILE:", profile);


  if (!profile || (profile.role !== UserRole.TEACHER && profile.role !== UserRole.SUPER_ADMIN)) {
    // You can decide to return null or throw an error here
    return null;
  }

  return profile;
}