<?php

declare(strict_types=1);

namespace KupShop\CatalogElasticBundle\Filters;

use KupShop\CatalogBundle\ProductList\DynamicFilterAttributes;
use KupShop\CatalogElasticBundle\DataContext\ElasticFilterSpecContext;
use KupShop\CatalogElasticBundle\DataContext\ElasticFilterValuesContext;
use KupShop\CatalogElasticBundle\Elastica\QueryBuilder;

class Campaigns extends ElasticFilter
{
    use QueryBuilder;

    public const ELASTIC_FIELD_NAME = 'filter_campaigns';

    public function getAggregations(DynamicFilterAttributes $attributes): iterable
    {
        if (!$attributes->campaigns) {
            return [];
        }

        yield $this->agg()
            ->terms(self::filterIdentifier())
            ->setField(self::ELASTIC_FIELD_NAME);
    }

    public function applyFilters(ElasticFilterSpecContext $ctx): void
    {
        if (!$ctx->value) {
            return;
        }

        $filter = $this->query()->terms(self::ELASTIC_FIELD_NAME, (array) $ctx->value);

        $ctx->set(self::filterIdentifier(), $filter);
    }

    public function collectValues(ElasticFilterValuesContext $ctx): void
    {
        $aggregations = $ctx->getTargetAggregations();
        if (empty($aggregations)) {
            return;
        }

        $values = [];

        foreach ($aggregations as $aggregation) {
            foreach ($aggregation['buckets'] as $bucket) {
                $values[$bucket['key']] = [
                    'count' => $bucket['doc_count'],
                ];
            }
        }

        $ctx->set(self::filterIdentifier(), $values);
    }
}
