// Guards for admin impersonation: a target may be impersonated only when they
// are neither a global admin (admin-plugin role) nor a configured super-admin
// (SUPER_ADMIN_EMAILS). Mirrors the better-auth admin-plugin admin-target block
// with defense-in-depth on the allow-list.
import { describe, expect, test } from "bun:test";
import { env } from "@/env";
import { isImpersonable } from "./impersonation";

describe("isImpersonable", () => {
  test("allows a plain user (role 'user', non-listed email)", () => {
    expect(
      isImpersonable({ role: "user", email: "someone@example.invalid" }),
    ).toBe(true);
  });

  test("allows when role is null/empty (default user)", () => {
    expect(isImpersonable({ role: null, email: "x@example.invalid" })).toBe(
      true,
    );
    expect(isImpersonable({ role: "", email: "x@example.invalid" })).toBe(true);
  });

  test("refuses a global admin (role 'admin')", () => {
    expect(isImpersonable({ role: "admin", email: "x@example.invalid" })).toBe(
      false,
    );
  });

  test("refuses an admin listed among comma-separated roles", () => {
    expect(
      isImpersonable({ role: "user,admin", email: "x@example.invalid" }),
    ).toBe(false);
  });

  const listed = (env.SUPER_ADMIN_EMAILS ?? "")
    .split(",")
    .map((e) => e.trim())
    .filter(Boolean);

  test.skipIf(listed.length === 0)(
    "refuses a configured super-admin even with role 'user'",
    () => {
      // Allow-list is the real authority: refuse even if the role was never
      // stamped admin (e.g. a pre-bridge account).
      expect(isImpersonable({ role: "user", email: listed[0] })).toBe(false);
    },
  );
});
