// src/lib/admin/impersonation.ts — pure guards for admin impersonation.
// Kept OUT of the "use server" actions module (which may only export async
// functions) so the decision logic stays unit-testable.
import { isSuperAdmin } from "@/lib/auth/super-admin";

/**
 * Defense in depth: a target user may be impersonated only when they are NOT a
 * global admin (admin-plugin `role`) AND NOT a configured super-admin
 * (SUPER_ADMIN_EMAILS). The better-auth admin plugin already blocks admin
 * targets — we never grant the `impersonate-admins` permission — but the
 * super-admin allow-list (not the role) is our real authority, so re-check it
 * here in case a super-admin's role was never stamped (e.g. pre-bridge account).
 */
export function isImpersonable(target: {
  role: string | null | undefined;
  email: string | null | undefined;
}): boolean {
  const roles = (target.role ?? "")
    .split(",")
    .map((r) => r.trim())
    .filter(Boolean);
  if (roles.includes("admin")) return false;
  if (isSuperAdmin(target.email)) return false;
  return true;
}
