package at.procon.dip.search.plan;

import at.procon.dip.search.api.SearchExecutionContext;
import at.procon.dip.search.api.SearchExecutionPlan;
import at.procon.dip.search.dto.SearchEngineType;
import at.procon.dip.search.dto.SearchMode;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.stereotype.Component;

@Component
public class DefaultSearchPlanner implements SearchPlanner {

    @Override
    public SearchExecutionPlan plan(SearchExecutionContext context) {
        Set<SearchMode> modes = context.getRequest().getModes();
        if (modes == null || modes.isEmpty()) {
            modes = Set.of(SearchMode.HYBRID);
        }

        Set<SearchEngineType> engines = new LinkedHashSet<>();
        if (modes.contains(SearchMode.HYBRID) || modes.contains(SearchMode.FULLTEXT)) {
            engines.add(SearchEngineType.POSTGRES_FULLTEXT);
        }
        if (modes.contains(SearchMode.HYBRID) || modes.contains(SearchMode.TRIGRAM)) {
            engines.add(SearchEngineType.POSTGRES_TRIGRAM);
        }
        if (modes.contains(SearchMode.HYBRID) || modes.contains(SearchMode.SEMANTIC)) {
            engines.add(SearchEngineType.PGVECTOR_SEMANTIC);
        }

        return SearchExecutionPlan.builder()
                .engines(new ArrayList<>(engines))
                .collapseByDocument(context.getRequest().isCollapseByDocument())
                .sortMode(context.getRequest().getSortMode())
                .build();
    }
}
