import { describe, expect, it } from "vitest";
import {
  canManageTenantScopedUsers,
  canManageUserInTenantScope,
  isSuperAdminRole,
  normalizeAdminRole,
  ROLE_SUPER_ADMIN,
  ROLE_USER,
} from "./roles";

describe("admin role helpers", () => {
  it.each([
    ["super_admin", ROLE_SUPER_ADMIN],
    ["superadmin", ROLE_SUPER_ADMIN],
    ["super-admin", ROLE_SUPER_ADMIN],
    ["  SUPER-ADMIN  ", ROLE_SUPER_ADMIN],
    ["tenant_admin", ROLE_USER],
    ["tenantadmin", ROLE_USER],
    ["tenant-admin", ROLE_USER],
    ["admin", ROLE_USER],
    ["rp_admin", ROLE_USER],
    ["rpadmin", ROLE_USER],
    ["rp-admin", ROLE_USER],
    ["tenant_member", ROLE_USER],
    ["member", ROLE_USER],
    ["custom", ROLE_USER],
    ["", ROLE_USER],
  ])("normalizes %s to %s", (input, expected) => {
    expect(normalizeAdminRole(input)).toBe(expected);
  });

  it("detects super admin aliases", () => {
    expect(isSuperAdminRole("super-admin")).toBe(true);
    expect(isSuperAdminRole("admin")).toBe(false);
    expect(isSuperAdminRole(undefined)).toBe(false);
  });

  it("allows delegated tenant admins with manageable tenants to manage scoped users", () => {
    const profile = {
      id: "admin-user",
      role: "user",
      manageableTenants: [{ id: "tenant-1", slug: "tenant-a" }],
    };

    expect(canManageTenantScopedUsers(profile)).toBe(true);
    expect(
      canManageUserInTenantScope({
        profile,
        user: { id: "user-1", tenantSlug: "tenant-a" },
      }),
    ).toBe(true);
    expect(
      canManageUserInTenantScope({
        profile,
        user: { id: "user-2", tenantSlug: "tenant-b" },
      }),
    ).toBe(false);
  });

  it("does not treat ordinary tenant membership as delegated user management", () => {
    const profile = {
      id: "member-user",
      role: "user",
      tenantSlug: "tenant-a",
      manageableTenants: [],
    };

    expect(canManageTenantScopedUsers(profile)).toBe(false);
    expect(
      canManageUserInTenantScope({
        profile,
        user: { id: "user-1", tenantSlug: "tenant-a" },
      }),
    ).toBe(false);
  });
});
