package dev.lions.user.manager.resource;

import dev.lions.user.manager.dto.user.*;
import dev.lions.user.manager.service.UserService;
import jakarta.ws.rs.core.Response;
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 java.util.Collections;
import java.util.List;
import java.util.Optional;

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

@ExtendWith(MockitoExtension.class)
class UserResourceTest {

    @Mock
    UserService userService;

    @InjectMocks
    UserResource userResource;

    private static final String REALM = "test-realm";

    @Test
    void testSearchUsers() {
        UserSearchCriteriaDTO criteria = UserSearchCriteriaDTO.builder()
                .realmName(REALM)
                .searchTerm("test")
                .page(0)
                .pageSize(20)
                .build();

        UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
                .users(Collections.singletonList(UserDTO.builder().username("test").build()))
                .totalCount(1L)
                .build();

        when(userService.searchUsers(any())).thenReturn(mockResult);

        UserSearchResultDTO result = userResource.searchUsers(criteria);

        assertNotNull(result);
        assertEquals(1, result.getTotalCount());
    }

    @Test
    void testGetUserById() {
        UserDTO user = UserDTO.builder().id("1").username("testuser").build();
        when(userService.getUserById("1", REALM)).thenReturn(Optional.of(user));

        UserDTO result = userResource.getUserById("1", REALM);

        assertNotNull(result);
        assertEquals(user, result);
    }

    @Test
    void testGetUserByIdNotFound() {
        when(userService.getUserById("1", REALM)).thenReturn(Optional.empty());

        assertThrows(RuntimeException.class, () -> userResource.getUserById("1", REALM));
    }

    @Test
    void testGetAllUsers() {
        UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
                .users(Collections.emptyList())
                .totalCount(0L)
                .build();
        when(userService.getAllUsers(REALM, 0, 20)).thenReturn(mockResult);

        UserSearchResultDTO result = userResource.getAllUsers(REALM, 0, 20);

        assertNotNull(result);
        assertEquals(0, result.getTotalCount());
    }

    @Test
    void testCreateUser() {
        UserDTO newUser = UserDTO.builder().username("newuser").email("new@test.com").build();
        UserDTO createdUser = UserDTO.builder().id("123").username("newuser").email("new@test.com").build();

        when(userService.createUser(any(), eq(REALM))).thenReturn(createdUser);

        Response response = userResource.createUser(newUser, REALM);

        assertEquals(201, response.getStatus());
        assertEquals(createdUser, response.getEntity());
    }

    @Test
    void testUpdateUser() {
        UserDTO updateUser = UserDTO.builder()
                .username("updated")
                .prenom("John")
                .nom("Doe")
                .email("john.doe@test.com")
                .build();
        UserDTO updatedUser = UserDTO.builder()
                .id("1")
                .username("updated")
                .prenom("John")
                .nom("Doe")
                .email("john.doe@test.com")
                .build();

        when(userService.updateUser(eq("1"), any(), eq(REALM))).thenReturn(updatedUser);

        UserDTO result = userResource.updateUser("1", updateUser, REALM);

        assertNotNull(result);
        assertEquals(updatedUser, result);
    }

    @Test
    void testDeleteUser() {
        doNothing().when(userService).deleteUser("1", REALM, false);

        userResource.deleteUser("1", REALM, false);

        verify(userService).deleteUser("1", REALM, false);
    }

    @Test
    void testActivateUser() {
        doNothing().when(userService).activateUser("1", REALM);

        userResource.activateUser("1", REALM);

        verify(userService).activateUser("1", REALM);
    }

    @Test
    void testDeactivateUser() {
        doNothing().when(userService).deactivateUser("1", REALM, "reason");

        userResource.deactivateUser("1", REALM, "reason");

        verify(userService).deactivateUser("1", REALM, "reason");
    }

    @Test
    void testResetPassword() {
        doNothing().when(userService).resetPassword("1", REALM, "newpassword", true);

        PasswordResetRequestDTO request = PasswordResetRequestDTO.builder()
                .password("newpassword")
                .temporary(true)
                .build();

        userResource.resetPassword("1", REALM, request);

        verify(userService).resetPassword("1", REALM, "newpassword", true);
    }

    @Test
    void testSendVerificationEmail() {
        doNothing().when(userService).sendVerificationEmail("1", REALM);

        userResource.sendVerificationEmail("1", REALM);

        verify(userService).sendVerificationEmail("1", REALM);
    }

    @Test
    void testLogoutAllSessions() {
        when(userService.logoutAllSessions("1", REALM)).thenReturn(5);

        SessionsRevokedDTO result = userResource.logoutAllSessions("1", REALM);

        assertNotNull(result);
        assertEquals(5, result.getCount());
    }

    @Test
    void testGetActiveSessions() {
        when(userService.getActiveSessions("1", REALM)).thenReturn(Collections.singletonList("session-1"));

        List<String> result = userResource.getActiveSessions("1", REALM);

        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals("session-1", result.get(0));
    }
}
