import { getCurrentUser } from "./session";
import type { User } from "@/lib/schema/db";

/**
 * Admin access control based on ADMIN_EMAILS environment variable.
 * Comma-separated list of email addresses that have admin privileges.
 */

const ADMIN_EMAILS: Set<string> = new Set(
  (process.env.ADMIN_EMAILS || "")
    .split(",")
    .map((e) => e.trim().toLowerCase())
    .filter(Boolean)
);

/** Checks whether the given email address belongs to an admin. */
export function isAdmin(email: string | null | undefined): boolean {
  if (!email) return false;
  return ADMIN_EMAILS.has(email.trim().toLowerCase());
}

/**
 * Server-side guard: resolves the current session and verifies admin status.
 * Returns the user if admin, or null otherwise.
 */
export async function getAdminUser(): Promise<User | null> {
  const user = await getCurrentUser();
  if (!user) return null;
  if (!isAdmin(user.email)) return null;
  return user;
}
