// src/lib/auth/super-admin.ts — god-mode gate via SUPER_ADMIN_EMAILS (env).
import { headers } from "next/headers";
import { env } from "@/env";
import { auth } from "@/lib/auth";

/** Pure: is `email` present in a comma-separated allow-list (case-insensitive)? */
export function emailInCsv(
  email: string | null | undefined,
  csv: string,
): boolean {
  if (!email) return false;
  const target = email.trim().toLowerCase();
  return csv
    .split(",")
    .map((e) => e.trim().toLowerCase())
    .filter(Boolean)
    .includes(target);
}

export function isSuperAdmin(email: string | null | undefined): boolean {
  return emailInCsv(email, env.SUPER_ADMIN_EMAILS ?? "");
}

/** Reads the session email and returns whether the current user is super-admin.
 *  God-mode must not authenticate off the 5-min cookie cache — force a DB read
 *  (disableCookieCache) so a revoked/expired session can't pass this gate on a
 *  device still holding a valid cache cookie. */
export async function isCurrentUserSuperAdmin(): Promise<boolean> {
  const session = await auth.api.getSession({
    headers: await headers(),
    query: { disableCookieCache: true },
  });
  return isSuperAdmin(session?.user?.email);
}

/** Throws if the current user is not a super-admin. Use to gate god-mode actions. */
export async function assertSuperAdmin(): Promise<void> {
  if (!(await isCurrentUserSuperAdmin())) {
    throw new Error("Forbidden: super-admin only");
  }
}

/** Shape returned by getSuperAdminSession — the live session/user plus whether
 *  the user has 2FA enabled (the God-Mode hard requirement). */
export interface SuperAdminSession {
  session: Awaited<ReturnType<typeof auth.api.getSession>>;
  user: NonNullable<Awaited<ReturnType<typeof auth.api.getSession>>>["user"];
  twoFactorEnabled: boolean;
}

/**
 * Returns the current session IF the user is a super-admin, else null. Forces a
 * fresh DB read (disableCookieCache) — same rationale as isCurrentUserSuperAdmin:
 * God Mode must never authenticate off the 5-min cookie cache. Also surfaces the
 * twoFactorEnabled flag (the `twoFactor` plugin column on the user) so callers
 * can enforce the mandatory-2FA gate without a second round-trip.
 */
export async function getSuperAdminSession(): Promise<SuperAdminSession | null> {
  const session = await auth.api.getSession({
    headers: await headers(),
    query: { disableCookieCache: true },
  });
  if (!session?.user || !isSuperAdmin(session.user.email)) return null;
  // `disableCookieCache` above forces a fresh user fetch, so twoFactorEnabled
  // reflects a just-completed enrollment on the very next request.
  const twoFactorEnabled = Boolean(
    (session.user as { twoFactorEnabled?: boolean }).twoFactorEnabled,
  );
  return { session, user: session.user, twoFactorEnabled };
}

/**
 * Throws unless the caller is a super-admin AND has 2FA enabled. Use to gate the
 * most sensitive God-Mode server actions (the same 2FA wall the (superadmin)
 * shell enforces at the UI layer — re-checked server-side here).
 */
export async function assertSuperAdminWith2FA(): Promise<void> {
  const ctx = await getSuperAdminSession();
  if (!ctx) throw new Error("Forbidden: super-admin only");
  if (!ctx.twoFactorEnabled) {
    throw new Error("Forbidden: 2FA required for God Mode");
  }
}
