package dev.lions.user.manager.service.impl;

import dev.lions.user.manager.client.KeycloakAdminClient;
import dev.lions.user.manager.dto.role.RoleAssignmentDTO;
import dev.lions.user.manager.dto.role.RoleDTO;
import dev.lions.user.manager.enums.role.TypeRole;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.*;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

/**
 * Tests d'intégration pour RoleServiceImpl - Cas limites et branches conditionnelles complexes
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class RoleServiceImplIntegrationTest {

    @Mock
    private KeycloakAdminClient keycloakAdminClient;

    @Mock
    private Keycloak keycloakInstance;

    @Mock
    private RealmResource realmResource;

    @Mock
    private RolesResource rolesResource;

    @Mock
    private RoleResource roleResource;

    @Mock
    private UsersResource usersResource;

    @Mock
    private UserResource userResource;

    @Mock
    private RoleMappingResource roleMappingResource;

    @Mock
    private RoleScopeResource roleScopeResource;

    @Mock
    private ClientsResource clientsResource;

    @Mock
    private ClientResource clientResource;

    @InjectMocks
    private RoleServiceImpl roleService;

    private static final String REALM = "test-realm";
    private static final String USER_ID = "user-123";
    private static final String ROLE_NAME = "admin";
    private static final String CLIENT_NAME = "test-client";
    private static final String ROLE_ID = "role-123";

    // ==================== Tests getRoleByName - Cas limites ====================

    @Test
    void testGetRoleByName_RealmRole_Success() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setName(ROLE_NAME);
        roleRep.setId(ROLE_ID);
        when(roleResource.toRepresentation()).thenReturn(roleRep);

        Optional<RoleDTO> result = roleService.getRoleByName(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);

        assertTrue(result.isPresent());
        assertEquals(ROLE_NAME, result.get().getName());
    }

    @Test
    void testGetRoleByName_RealmRole_NotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenThrow(new jakarta.ws.rs.NotFoundException());

        Optional<RoleDTO> result = roleService.getRoleByName(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);

        assertFalse(result.isPresent());
    }

    @Test
    void testGetRoleByName_ClientRole_Success() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);

        ClientRepresentation client = new ClientRepresentation();
        client.setId("client-123");
        client.setClientId(CLIENT_NAME);
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
        when(clientsResource.get("client-123")).thenReturn(clientResource);
        when(clientResource.roles()).thenReturn(rolesResource);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setName(ROLE_NAME);
        roleRep.setId(ROLE_ID);
        when(roleResource.toRepresentation()).thenReturn(roleRep);

        Optional<RoleDTO> result = roleService.getRoleByName(ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);

        assertTrue(result.isPresent());
        assertEquals(ROLE_NAME, result.get().getName());
    }

    @Test
    void testGetRoleByName_ClientRole_ClientNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());

        Optional<RoleDTO> result = roleService.getRoleByName(ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);

        assertFalse(result.isPresent());
    }

    @Test
    void testGetRoleByName_ClientRole_NullClientName() {
        Optional<RoleDTO> result = roleService.getRoleByName(ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, null);

        assertFalse(result.isPresent());
    }

    // ==================== Tests assignRolesToUser - Cas limites ====================

    @Test
    void testAssignRolesToUser_RealmRole_Success() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(realmResource.users()).thenReturn(usersResource);
        when(usersResource.get(USER_ID)).thenReturn(userResource);
        when(userResource.roles()).thenReturn(roleMappingResource);
        when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setName(ROLE_NAME);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(roleRep);

        RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
            .userId(USER_ID)
            .realmName(REALM)
            .typeRole(TypeRole.REALM_ROLE)
            .roleNames(List.of(ROLE_NAME))
            .build();

        roleService.assignRolesToUser(assignment);

        verify(roleScopeResource).add(anyList());
    }

    @Test
    void testAssignRolesToUser_ClientRole_Success() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        when(realmResource.users()).thenReturn(usersResource);
        when(usersResource.get(USER_ID)).thenReturn(userResource);
        when(userResource.roles()).thenReturn(roleMappingResource);

        ClientRepresentation client = new ClientRepresentation();
        client.setId("client-123");
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
        when(clientsResource.get("client-123")).thenReturn(clientResource);
        when(clientResource.roles()).thenReturn(rolesResource);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
        when(roleMappingResource.clientLevel("client-123")).thenReturn(roleScopeResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setName(ROLE_NAME);
        when(roleResource.toRepresentation()).thenReturn(roleRep);

        RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
            .userId(USER_ID)
            .realmName(REALM)
            .typeRole(TypeRole.CLIENT_ROLE)
            .clientName(CLIENT_NAME)
            .roleNames(List.of(ROLE_NAME))
            .build();

        roleService.assignRolesToUser(assignment);

        verify(roleScopeResource).add(anyList());
    }

    @Test
    void testAssignRolesToUser_ClientRole_NullClientName() {
        RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
            .userId(USER_ID)
            .realmName(REALM)
            .typeRole(TypeRole.CLIENT_ROLE)
            .clientName(null)
            .roleNames(List.of(ROLE_NAME))
            .build();

        assertThrows(IllegalArgumentException.class, () -> roleService.assignRolesToUser(assignment));
    }

    // ==================== Tests revokeRolesFromUser - Cas limites ====================

    @Test
    void testRevokeRolesFromUser_RealmRole_Success() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(realmResource.users()).thenReturn(usersResource);
        when(usersResource.get(USER_ID)).thenReturn(userResource);
        when(userResource.roles()).thenReturn(roleMappingResource);
        when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setName(ROLE_NAME);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(roleRep);

        RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
            .userId(USER_ID)
            .realmName(REALM)
            .typeRole(TypeRole.REALM_ROLE)
            .roleNames(List.of(ROLE_NAME))
            .build();

        roleService.revokeRolesFromUser(assignment);

        verify(roleScopeResource).remove(anyList());
    }

    @Test
    void testRevokeRolesFromUser_ClientRole_NullClientName() {
        RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
            .userId(USER_ID)
            .realmName(REALM)
            .typeRole(TypeRole.CLIENT_ROLE)
            .clientName(null)
            .roleNames(List.of(ROLE_NAME))
            .build();

        assertThrows(IllegalArgumentException.class, () -> roleService.revokeRolesFromUser(assignment));
    }

    // ==================== Tests getAllUserRoles - Cas limites ====================

    @Test
    void testGetAllUserRoles_WithRealmAndClientRoles() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.users()).thenReturn(usersResource);
        when(usersResource.get(USER_ID)).thenReturn(userResource);
        when(userResource.roles()).thenReturn(roleMappingResource);
        when(realmResource.clients()).thenReturn(clientsResource);

        // Mock realm roles - getUserRealmRoles is called first
        RoleScopeResource realmRoleScope = mock(RoleScopeResource.class);
        RoleRepresentation realmRole = new RoleRepresentation();
        realmRole.setName("realm-role");
        when(roleMappingResource.realmLevel()).thenReturn(realmRoleScope);
        when(realmRoleScope.listAll()).thenReturn(List.of(realmRole));

        // Mock client roles - getAllUserRoles calls getUserClientRoles for each client
        // getAllUserRoles calls getUserClientRoles with client.getClientId() (CLIENT_NAME)
        // getUserClientRoles then finds the client by clientId and uses the internal ID
        ClientRepresentation client = new ClientRepresentation();
        client.setId("client-123"); // Internal ID
        client.setClientId(CLIENT_NAME); // Client ID
        when(clientsResource.findAll()).thenReturn(List.of(client));
        
        // getUserClientRoles finds client by clientId
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
        
        // getUserClientRoles uses internal ID for clientLevel
        RoleScopeResource clientRoleScope = mock(RoleScopeResource.class);
        when(roleMappingResource.clientLevel("client-123")).thenReturn(clientRoleScope);
        RoleRepresentation clientRole = new RoleRepresentation();
        clientRole.setName("client-role");
        when(clientRoleScope.listAll()).thenReturn(List.of(clientRole));

        List<RoleDTO> result = roleService.getAllUserRoles(USER_ID, REALM);

        assertNotNull(result);
        assertTrue(result.size() >= 1);
    }

    @Test
    void testGetAllUserRoles_WithExceptionInClientRoles() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.users()).thenReturn(usersResource);
        when(usersResource.get(USER_ID)).thenReturn(userResource);
        when(userResource.roles()).thenReturn(roleMappingResource);
        when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
        when(realmResource.clients()).thenReturn(clientsResource);

        // Mock realm roles
        RoleRepresentation realmRole = new RoleRepresentation();
        realmRole.setName("realm-role");
        when(roleScopeResource.listAll()).thenReturn(List.of(realmRole));

        // Exception when getting clients
        when(clientsResource.findAll()).thenThrow(new RuntimeException("Error"));

        // Should not throw, just log warning
        List<RoleDTO> result = roleService.getAllUserRoles(USER_ID, REALM);

        assertNotNull(result);
        assertEquals(1, result.size()); // Only realm roles
    }

    // ==================== Tests addCompositeRoles - Cas limites ====================

    @Test
    void testAddCompositeRoles_RealmRole_ParentNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.list()).thenReturn(Collections.emptyList());

        // getRoleById returns Optional.empty() when role not found, which causes NotFoundException
        assertThrows(jakarta.ws.rs.NotFoundException.class, () -> 
            roleService.addCompositeRoles(ROLE_ID, List.of("child-1"), REALM, TypeRole.REALM_ROLE, null));
    }

    @Test
    void testAddCompositeRoles_RealmRole_ChildNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);

        RoleRepresentation parentRole = new RoleRepresentation();
        parentRole.setId(ROLE_ID);
        parentRole.setName("parent");
        // Mock getRoleById to return parent role
        when(rolesResource.list()).thenReturn(List.of(parentRole));
        when(rolesResource.get("parent")).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(parentRole);

        // Child role not found - getRealmRoleById returns empty for child
        // This means childRoleNames will be empty, so addComposites won't be called
        // Should not throw, just log warning and skip
        roleService.addCompositeRoles(ROLE_ID, List.of("child-id"), REALM, TypeRole.REALM_ROLE, null);

        // Verify that get was called for parent role - use lenient to avoid unnecessary stubbing
        verify(rolesResource, atLeastOnce()).list();
    }

    @Test
    void testAddCompositeRoles_ClientRole_ClientNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        
        // Mock getRoleById to return a role
        RoleRepresentation parentRole = new RoleRepresentation();
        parentRole.setId(ROLE_ID);
        parentRole.setName("parent");
        when(rolesResource.list()).thenReturn(List.of(parentRole));
        when(rolesResource.get("parent")).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(parentRole);
        
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());

        // When client not found, it throws IllegalArgumentException in removeCompositeRoles
        // But in addCompositeRoles, it first checks getRoleById which may throw NotFoundException
        // Actually, looking at the code, if client is not found, it throws IllegalArgumentException
        // But getRoleById might throw NotFoundException first
        assertThrows(jakarta.ws.rs.NotFoundException.class, () -> 
            roleService.addCompositeRoles(ROLE_ID, List.of("child-1"), REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
    }

    // ==================== Tests removeCompositeRoles - Cas limites ====================

    @Test
    void testRemoveCompositeRoles_RealmRole_ChildNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);

        RoleRepresentation parentRole = new RoleRepresentation();
        parentRole.setId(ROLE_ID);
        parentRole.setName("parent");
        when(rolesResource.list()).thenReturn(List.of(parentRole));

        // Child role not found - getRealmRoleById returns empty, so childRoleNames will be empty
        // Should not throw, just log warning and skip
        roleService.removeCompositeRoles(ROLE_ID, List.of("child-id"), REALM, TypeRole.REALM_ROLE, null);

        // Verify that list was called
        verify(rolesResource, atLeastOnce()).list();
    }

    @Test
    void testRemoveCompositeRoles_ClientRole_ClientNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        
        // Mock getRoleById to return a role
        RoleRepresentation parentRole = new RoleRepresentation();
        parentRole.setId(ROLE_ID);
        parentRole.setName("parent");
        when(rolesResource.list()).thenReturn(List.of(parentRole));
        when(rolesResource.get("parent")).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(parentRole);
        
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());

        // When client not found, it throws IllegalArgumentException
        // But getRoleById might throw NotFoundException first
        assertThrows(jakarta.ws.rs.NotFoundException.class, () -> 
            roleService.removeCompositeRoles(ROLE_ID, List.of("child-1"), REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
    }

    // ==================== Tests getAllRealmRoles - Cas limites ====================

    @Test
    void testGetAllRealmRoles_RealmNotFound() {
        // realmExists returns false, so it throws IllegalArgumentException
        when(keycloakAdminClient.realmExists(REALM)).thenReturn(false);

        // But if realmExists throws an exception, it might be wrapped
        // Let's test both cases
        try {
            roleService.getAllRealmRoles(REALM);
            fail("Should have thrown an exception");
        } catch (IllegalArgumentException e) {
            // Expected when realmExists returns false
            assertTrue(e.getMessage().contains("n'existe pas"));
        } catch (RuntimeException e) {
            // Also possible if realmExists throws
            assertTrue(e.getMessage().contains("n'existe pas") || 
                      e.getMessage().contains("récupération des rôles realm"));
        }
    }

    @Test
    void testGetAllRealmRoles_NotFoundException() {
        when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.list()).thenThrow(new jakarta.ws.rs.NotFoundException());

        assertThrows(IllegalArgumentException.class, () -> 
            roleService.getAllRealmRoles(REALM));
    }

    @Test
    void testGetAllRealmRoles_ExceptionWith404() {
        when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.list()).thenThrow(new RuntimeException("Server response is: 404"));

        assertThrows(IllegalArgumentException.class, () -> 
            roleService.getAllRealmRoles(REALM));
    }

    @Test
    void testGetAllRealmRoles_ExceptionWithNotFound() {
        when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.list()).thenThrow(new RuntimeException("Not Found"));

        assertThrows(IllegalArgumentException.class, () -> 
            roleService.getAllRealmRoles(REALM));
    }

    // ==================== Tests getAllClientRoles - Cas limites ====================

    @Test
    void testGetAllClientRoles_ClientNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());

        List<RoleDTO> result = roleService.getAllClientRoles(REALM, CLIENT_NAME);

        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

    // ==================== Tests createClientRole - Cas limites ====================

    @Test
    void testCreateClientRole_ClientNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());

        RoleDTO roleDTO = RoleDTO.builder()
            .name(ROLE_NAME)
            .build();

        assertThrows(IllegalArgumentException.class, () -> 
            roleService.createClientRole(roleDTO, REALM, CLIENT_NAME));
    }

    @Test
    void testCreateClientRole_RoleAlreadyExists() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.clients()).thenReturn(clientsResource);

        ClientRepresentation client = new ClientRepresentation();
        client.setId("client-123");
        when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
        when(clientsResource.get("client-123")).thenReturn(clientResource);
        when(clientResource.roles()).thenReturn(rolesResource);
        when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
        when(roleResource.toRepresentation()).thenReturn(new RoleRepresentation());

        RoleDTO roleDTO = RoleDTO.builder()
            .name(ROLE_NAME)
            .build();

        assertThrows(IllegalArgumentException.class, () -> 
            roleService.createClientRole(roleDTO, REALM, CLIENT_NAME));
    }

    // ==================== Tests countUsersWithRole - Cas limites ====================

    @Test
    void testCountUsersWithRole_RoleNotFound() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(rolesResource.list()).thenReturn(Collections.emptyList());

        long count = roleService.countUsersWithRole(ROLE_ID, REALM, TypeRole.REALM_ROLE, null);

        assertEquals(0, count);
    }

    @Test
    void testCountUsersWithRole_Exception() {
        when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
        when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
        when(realmResource.roles()).thenReturn(rolesResource);
        when(realmResource.users()).thenReturn(usersResource);

        RoleRepresentation roleRep = new RoleRepresentation();
        roleRep.setId(ROLE_ID);
        roleRep.setName(ROLE_NAME);
        when(rolesResource.list()).thenReturn(List.of(roleRep));
        when(usersResource.list()).thenThrow(new RuntimeException("Error"));

        long count = roleService.countUsersWithRole(ROLE_ID, REALM, TypeRole.REALM_ROLE, null);

        assertEquals(0, count); // Should return 0 on exception
    }
}

