package org.raddatz.familienarchiv.user;

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 org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.user.AppUserRepository;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class UserSearchServiceTest {

    @Mock AppUserRepository userRepository;
    @InjectMocks UserSearchService userSearchService;

    // ─── search ───────────────────────────────────────────────────────────────

    @Test
    void search_returnsEmpty_whenQueryIsNull() {
        List<AppUser> result = userSearchService.search(null);

        assertThat(result).isEmpty();
        verify(userRepository, never()).searchByEmailOrName(any(), any());
    }

    @Test
    void search_returnsEmpty_whenQueryIsBlank() {
        List<AppUser> result = userSearchService.search("   ");

        assertThat(result).isEmpty();
        verify(userRepository, never()).searchByEmailOrName(any(), any());
    }

    @Test
    void search_delegatesToRepository_whenQueryIsNonBlank() {
        AppUser user = AppUser.builder().id(UUID.randomUUID()).email("hans@example.com").build();
        when(userRepository.searchByEmailOrName(eq("hans"), any(PageRequest.class)))
                .thenReturn(List.of(user));

        List<AppUser> result = userSearchService.search("hans");

        assertThat(result).containsExactly(user);
        verify(userRepository).searchByEmailOrName(eq("hans"), any(PageRequest.class));
    }

    @Test
    void search_trimsQuery_beforeDelegating() {
        when(userRepository.searchByEmailOrName(eq("hans"), any(PageRequest.class)))
                .thenReturn(List.of());

        userSearchService.search("  hans  ");

        verify(userRepository).searchByEmailOrName(eq("hans"), any(PageRequest.class));
    }
}
