package com.vaessl.app.search;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.vaessl.app.exception.WrongServiceTypeException;

@Service
public class SearchService {

    private final Map<String, SearchProvider> providerRegistry;

    public SearchService(List<SearchProvider> providers) {
        this.providerRegistry = Map.copyOf(providers.stream()
                .collect(Collectors.toMap(SearchProvider::getServiceType, p -> p)));
    }

    /**
     * Dispatches the paged search request to the provider registered for
     * {@link SearchRequest#serviceType()}.
     *
     * @param request the search request
     * @param pageable the Pageable interface
     * @return results returned by the matching provider
     * @throws WrongServiceTypeException if no provider is registered for the given service type
     */
    public Page<SearchResponse> search(SearchRequest request, Pageable pageable) {

        SearchProvider provider = providerRegistry.get(request.serviceType());

        if (provider == null) {
            throw new WrongServiceTypeException();
        }

        return provider.getSearchResults(request, pageable);
    }
}
