package dev.lions.user.manager.client.view;

import dev.lions.user.manager.client.service.RealmServiceClient;
import dev.lions.user.manager.client.service.UserServiceClient;
import dev.lions.user.manager.dto.user.UserDTO;
import dev.lions.user.manager.dto.user.UserSearchCriteriaDTO;
import dev.lions.user.manager.dto.user.UserSearchResultDTO;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.PartialViewContext;
import org.junit.jupiter.api.AfterEach;
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.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.primefaces.PrimeFaces;

import java.lang.reflect.Field;
import java.util.Collections;

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

@ExtendWith(MockitoExtension.class)
class UserListBeanTest {

    @Mock
    UserServiceClient userServiceClient;

    @Mock
    RealmServiceClient realmServiceClient;

    @Mock
    FacesContext facesContext;

    @Mock
    PartialViewContext partialViewContext;

    @InjectMocks
    UserListBean userListBean;

    MockedStatic<FacesContext> facesContextMock;
    MockedStatic<PrimeFaces> primeFacesMock;

    @BeforeEach
    void setUp() throws Exception {
        facesContextMock = mockStatic(FacesContext.class);
        facesContextMock.when(FacesContext::getCurrentInstance).thenReturn(facesContext);
        // Inject defaultRealm ET realmName via réflexion — realmName n'est pris de
        // defaultRealm que par @PostConstruct init() (non déclenché en unit-test).
        Field defaultRealmField = UserListBean.class.getDeclaredField("defaultRealm");
        defaultRealmField.setAccessible(true);
        defaultRealmField.set(userListBean, "lions-user-manager");
        Field realmNameField = UserListBean.class.getDeclaredField("realmName");
        realmNameField.setAccessible(true);
        realmNameField.set(userListBean, "lions-user-manager");
    }

    @AfterEach
    void tearDown() {
        if (primeFacesMock != null) primeFacesMock.close();
        facesContextMock.close();
    }

    @Test
    void testInit() {
        UserSearchResultDTO result = new UserSearchResultDTO();
        result.setUsers(Collections.singletonList(new UserDTO()));
        result.setTotalCount(1L);
        when(userServiceClient.searchUsers(any(UserSearchCriteriaDTO.class))).thenReturn(result);
        when(realmServiceClient.getAllRealms()).thenReturn(Collections.singletonList("lions-user-manager"));

        userListBean.init();

        // init() appelle loadStats() qui remplit kpiTotalUsers via searchUsers.
        // totalRecords est mis à jour par le LazyDataModel.load() — pas appelé ici.
        assertEquals(1L, userListBean.getKpiTotalUsers());
        assertNotNull(userListBean.getUsers());
    }

    @Test
    void testSearch() {
        // search() appelle PrimeFaces.current().isAjaxRequest() — il faut stubber le statique.
        PrimeFaces primeFaces = mock(PrimeFaces.class);
        primeFacesMock = mockStatic(PrimeFaces.class);
        primeFacesMock.when(PrimeFaces::current).thenReturn(primeFaces);
        when(primeFaces.isAjaxRequest()).thenReturn(false);

        userListBean.setCurrentPage(5);
        userListBean.setSearchText("test");
        userListBean.search();

        assertEquals(0, userListBean.getCurrentPage(), "search() doit reset currentPage à 0");
    }

    @Test
    void testActivateUser() {
        doNothing().when(userServiceClient).activateUser(any(String.class), any(String.class));

        userListBean.activateUser("1");

        verify(userServiceClient).activateUser(eq("1"), eq("lions-user-manager"));
        verify(facesContext).addMessage(any(), any(FacesMessage.class));
    }
}
