// Auto-assigned to all roles — hidden from UI
const AUTO_ASSIGNED_KEYS = new Set(["audit:logAuditEvent", "user-management:updateOwnProfile"]);

const GROUPS = [
  {
    label: "Manage Users",
    description: "Create, edit, activate, and deactivate user accounts",
    keys: [
      "user-management:createUser",
      "user-management:updateUser",
      "user-management:activateUser",
      "user-management:deactivateUser",
      "user-management:reactivateUser",
    ],
  },
  {
    label: "Assign Roles",
    description: "Assign and remove roles from users",
    keys: ["user-management:assignRoleToUser", "user-management:revokeRoleFromUser"],
  },
  {
    label: "Manage Roles & Permissions",
    description: "Create roles, manage permissions and their assignments",
    keys: [
      "user-management:createRole",
      "user-management:createPermission",
      "user-management:assignPermissionToRole",
      "user-management:revokePermissionFromRole",
    ],
  },
] as const;

interface Permission {
  id: string;
  key: string;
  description?: string | null;
}

export interface PermissionGroup {
  label: string;
  description: string;
  permissions: Permission[];
}

export function groupPermissions(permissions: Permission[]): PermissionGroup[] {
  const keyToPermission = new Map(permissions.map((p) => [p.key, p]));

  return GROUPS.map((group) => ({
    label: group.label,
    description: group.description,
    permissions: group.keys
      .map((key) => keyToPermission.get(key))
      .filter((p): p is Permission => p != null),
  })).filter((group) => group.permissions.length > 0);
}

export function isAutoAssigned(permission: Permission): boolean {
  return AUTO_ASSIGNED_KEYS.has(permission.key);
}
