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

export async function requireUser() {
  const cookieStore = await cookies();
  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    { cookies: { getAll() { return cookieStore.getAll() } } }
  );

  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;

  const profile = await db.profile.findUnique({ where: { id: user.id } }).catch((error) => {
    console.error("Failed to load profile for authenticated user.", error);
    return null;
  });
  if (profile) return profile;

  // Keep authenticated flows working even if profile lookup fails.
  return {
    id: user.id,
    email: user.email ?? "unknown@acve.local",
    fullName: (user.user_metadata?.full_name as string | undefined) ?? null,
    avatarUrl: null,
    role: UserRole.LEARNER,
    createdAt: new Date(0),
    updatedAt: new Date(0),
  };
}
