package at.procon.dip.search.web;

import at.procon.dip.search.dto.SearchDebugResponse;
import at.procon.dip.search.dto.SearchMetricsResponse;
import at.procon.dip.search.dto.SearchRequest;
import at.procon.dip.search.dto.SearchResponse;
import at.procon.dip.search.service.SearchOrchestrator;
import at.procon.dip.search.spi.SearchDocumentScope;
import jakarta.validation.Valid;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;

@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
public class GenericSearchController {

    private final SearchOrchestrator searchOrchestrator;

    @PostMapping
    public SearchResponse search(@Valid @RequestBody SearchRequest request) {
        return searchOrchestrator.search(request, buildScope(request));
    }

    @PostMapping("/debug")
    public SearchDebugResponse debug(@Valid @RequestBody SearchRequest request) {
        return searchOrchestrator.debug(request, buildScope(request));
    }

    @GetMapping("/metrics")
    public SearchMetricsResponse metrics() {
        return searchOrchestrator.metrics();
    }

    private SearchDocumentScope buildScope(SearchRequest request) {
        String scopeLanguage = (request.getLanguageCodes() == null || request.getLanguageCodes().isEmpty())
                ? null
                : request.getLanguageCodes().iterator().next();
        return new SearchDocumentScope(
                Set.of(),
                request.getDocumentTypes(),
                request.getDocumentFamilies(),
                request.getVisibilities(),
                scopeLanguage,
                null
        );
    }
}
