import "server-only";
import { auth } from "./auth";

/**
 * Lightweight view-model of the current viewer, shaped for rendering gates
 * (show/hide the "Join OrthoGlobe" CTA, show the admin link, etc.). Returns
 * a stable shape so callers can destructure without null-checks.
 *
 * Usage in server components:
 *
 *     const viewer = await getViewer();
 *     if (!viewer.signedIn) { ...guest... }
 */
export type Viewer = {
  signedIn: boolean;
  userId: string | null;
  name: string | null;
  role: "admin" | "user" | null;
};

const GUEST: Viewer = {
  signedIn: false,
  userId: null,
  name: null,
  role: null,
};

export async function getViewer(): Promise<Viewer> {
  const session = await auth().catch(() => null);
  const user = session?.user as
    | { id?: string; name?: string | null; role?: string }
    | undefined;
  if (!user?.id) return GUEST;
  return {
    signedIn: true,
    userId: user.id,
    name: user.name ?? null,
    role: user.role === "admin" ? "admin" : "user",
  };
}
