package at.procon.dip.search.rank;

import at.procon.dip.search.dto.SearchEngineType;
import at.procon.dip.search.dto.SearchHit;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
public class DefaultSearchScoreNormalizer implements SearchScoreNormalizer {

    @Override
    public List<SearchHit> normalize(SearchEngineType engineType, List<SearchHit> hits) {
        if (hits == null || hits.isEmpty()) {
            return List.of();
        }
        double max = hits.stream().mapToDouble(SearchHit::getRawScore).max().orElse(1.0d);
        double divisor = max > 0.0d ? max : 1.0d;
        return hits.stream()
                .map(hit -> hit.toBuilder()
                        .normalizedScore(clamp(hit.getRawScore() / divisor))
                        .build())
                .toList();
    }

    private double clamp(double value) {
        if (value < 0.0d) {
            return 0.0d;
        }
        if (value > 1.0d) {
            return 1.0d;
        }
        return value;
    }
}
