<?php
/**
 * Plumrocket Inc.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the End-user License Agreement
 * that is available through the world-wide-web at this URL:
 * http://wiki.plumrocket.net/wiki/EULA
 * If you are unable to obtain it through the world-wide-web, please
 * send an email to support@plumrocket.com so we can send you a copy immediately.
 *
 * @package     Plumrocket_ProductFilter
 * @copyright   Copyright (c) 2020 Plumrocket Inc. (http://www.plumrocket.com)
 * @license     http://wiki.plumrocket.net/wiki/EULA  End-user License Agreement
 */

declare(strict_types=1);

namespace Plumrocket\ProductFilter\Plugin\Elasticsearch;

use Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Dynamic;
use Magento\Framework\Search\Dynamic\DataProviderInterface;
use Magento\Framework\Search\Request\BucketInterface;
use Plumrocket\ProductFilter\Model\CatalogSearch\Model\ResourceModel\Fulltext\Collection\CurrentLoading;

/**
 * Temporary fix for
 * @link https://github.com/magento/magento2/issues/28919
 * TODO: remove after left support magento version with bug
 *
 * @since 3.2.12
 */
class SaveRealMaxAndMinPrices
{
    /**
     * @var \Plumrocket\ProductFilter\Model\CatalogSearch\Model\ResourceModel\Fulltext\Collection\CurrentLoading
     */
    private $currentLoadingCollection;

    /**
     * @param \Plumrocket\ProductFilter\Model\CatalogSearch\Model\ResourceModel\Fulltext\Collection\CurrentLoading $currentLoadingCollection
     */
    public function __construct(CurrentLoading $currentLoadingCollection)
    {
        $this->currentLoadingCollection = $currentLoadingCollection;
    }

    /**
     * @param \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Dynamic $subject
     * @param BucketInterface                                                  $bucket
     * @param Dimension[]                                                      $dimensions
     * @param array                                                            $queryResult
     * @param DataProviderInterface                                            $dataProvider
     */
    public function beforeBuild(
        \Magento\Elasticsearch\SearchAdapter\Aggregation\Builder\Dynamic $subject,
        \Magento\Framework\Search\Request\BucketInterface $bucket,
        array $dimensions,
        array $queryResult,
        DataProviderInterface $dataProvider
    ) {
        if (isset($queryResult['aggregations']['price_bucket']) && 'price_bucket' === $bucket->getName()) {
            $priceData = $queryResult['aggregations']['price_bucket'];
            $this->currentLoadingCollection->setPriceData($priceData);
        }
    }
}
