package dev.lions.user.manager.resource;

import dev.lions.user.manager.client.KeycloakAdminClient;
import io.quarkus.security.identity.SecurityIdentity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import jakarta.ws.rs.core.Response;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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

/**
 * Tests unitaires pour RealmResource
 */
@ExtendWith(MockitoExtension.class)
class RealmResourceTest {

    @Mock
    private KeycloakAdminClient keycloakAdminClient;

    @Mock
    private SecurityIdentity securityIdentity;

    @InjectMocks
    private RealmResource realmResource;

    @BeforeEach
    void setUp() {
        // Setup initial
    }

    @Test
    void testGetAllRealms_Success() {
        List<String> realms = Arrays.asList("master", "lions-user-manager", "btpxpress");
        when(keycloakAdminClient.getAllRealms()).thenReturn(realms);

        Response response = realmResource.getAllRealms();

        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        @SuppressWarnings("unchecked")
        List<String> responseRealms = (List<String>) response.getEntity();
        assertNotNull(responseRealms);
        assertEquals(3, responseRealms.size());
        assertEquals("master", responseRealms.get(0));
        verify(keycloakAdminClient).getAllRealms();
    }

    @Test
    void testGetAllRealms_EmptyList() {
        when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.emptyList());

        Response response = realmResource.getAllRealms();

        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        @SuppressWarnings("unchecked")
        List<String> responseRealms = (List<String>) response.getEntity();
        assertNotNull(responseRealms);
        assertTrue(responseRealms.isEmpty());
    }

    @Test
    void testGetAllRealms_Exception() {
        when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Keycloak connection error"));

        Response response = realmResource.getAllRealms();

        assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
        RealmResource.ErrorResponse errorResponse = (RealmResource.ErrorResponse) response.getEntity();
        assertNotNull(errorResponse);
        assertTrue(errorResponse.getMessage().contains("Erreur lors de la récupération des realms"));
    }

    @Test
    void testErrorResponse() {
        RealmResource.ErrorResponse errorResponse = new RealmResource.ErrorResponse("Test error");
        assertEquals("Test error", errorResponse.getMessage());

        errorResponse.setMessage("New error");
        assertEquals("New error", errorResponse.getMessage());
    }
}

