import { headers } from "next/headers";
import { auth } from "./auth";
import prisma from "./db";

export async function getCurrentUser() {
  try {
    const session = await auth.api.getSession({
      headers: await headers(),
    });

    if (!session) {
      return null;
    }

    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        bio: true,
        image: true,
        emailVerified: true,
        university: true,
        semester: true,
        countryOfOrigin: true,
        createdAt: true,
      },
    });

    return user;
  } catch {
    return null;
  }
}

export async function requireAuth() {
  const user = await getCurrentUser();
  if (!user) {
    throw new Error("Unauthorized");
  }
  return user;
}

export async function requireGuide() {
  const user = await requireAuth();
  if (user.role !== "GUIDE") {
    throw new Error("Forbidden: Guide access required");
  }
  return user;
}
