<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Factory\ResultSet;

use Elastica\ResultSet as ElasticaResultSet;
use MonsieurBiz\SyliusSearchPlugin\Model\Document\RangeFilter;
use MonsieurBiz\SyliusSearchPlugin\Model\Document\RangeFilterAwareInterface;
use MonsieurBiz\SyliusSearchPlugin\Model\Document\RangeFilterInterface;
use MonsieurBiz\SyliusSearchPlugin\Model\Document\ResultSetRangeFilter;

class PriceFilterFactory implements PriceFilterFactoryInterface
{
    public function create(ElasticaResultSet $resultSet = null): RangeFilterAwareInterface
    {
        $filter = new ResultSetRangeFilter();
        if (null !== $resultSet) {
            $filter->setFilter($this->buildPriceFilter($resultSet));
        }

        return $filter;
    }

    private function buildPriceFilter(ElasticaResultSet $resultSet): ?RangeFilterInterface
    {
        $aggregations = $resultSet->getAggregations();

        $priceAggregation = $aggregations['price'] ?? null;

        if (null === $priceAggregation || $priceAggregation['doc_count'] <= 0) {
            return null;
        }

        return new RangeFilter(
            'price',
            'monsieurbiz_searchplugin.filters.price_filter',
            'monsieurbiz_searchplugin.filters.price_min',
            'monsieurbiz_searchplugin.filters.price_max',
            (int) floor(($priceAggregation['values']['min'] ?? 0) / 100),
            (int) ceil(($priceAggregation['values']['max'] ?? 0) / 100),
        );
    }
}
