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

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 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 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
    FacesContext facesContext;

    @InjectMocks
    UserListBean userListBean;

    MockedStatic<FacesContext> facesContextMock;

    @BeforeEach
    void setUp() {
        facesContextMock = mockStatic(FacesContext.class);
        facesContextMock.when(FacesContext::getCurrentInstance).thenReturn(facesContext);
    }

    @AfterEach
    void tearDown() {
        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);

        userListBean.init();

        assertEquals(1, userListBean.getTotalRecords());
    }

    @Test
    void testSearch() {
        UserSearchResultDTO result = new UserSearchResultDTO();
        result.setUsers(Collections.singletonList(new UserDTO()));
        result.setTotalCount(10L);
        when(userServiceClient.searchUsers(any(UserSearchCriteriaDTO.class))).thenReturn(result);

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

        assertEquals(0, userListBean.getCurrentPage()); // Should reset to 0
    }

    // onPageChange removed as it does not exist in UserListBean
    @Test
    void testActivateUser() {
        doNothing().when(userServiceClient).activateUser(anyString(), anyString());
        // mock loadUsers calls searchUsers
        when(userServiceClient.searchUsers(any(UserSearchCriteriaDTO.class))).thenReturn(new UserSearchResultDTO());

        userListBean.activateUser("1");

        verify(userServiceClient).activateUser(eq("1"), anyString());
        verify(facesContext).addMessage(any(), any(FacesMessage.class));
    }
}
