<?php

namespace IQDEV\ElasticSearch\Search\Aggs;

use IQDEV\ElasticSearch\Esable;
use IQDEV\ElasticSearch\Search\BoolQuery\Query;
use IQDEV\ElasticSearch\Search\Nested;

final class Aggs implements Esable
{
    private ?AggsCollection $aggs = null;
    private ?Query $query = null;
    private ?Nested $nested = null;
    private ?Terms $terms = null;
    private ?Stats $stats = null;

    public function __construct(
        private string $key
    ) {
    }

    public function addAggs(Aggs $aggs): self
    {
        if (null === $this->aggs) {
            $this->aggs = new AggsCollection();
        }

        $this->aggs->add($aggs);

        return $this;
    }

    public function setQuery(?Query $query): self
    {
        $this->query = $query;

        return $this;
    }

    public function setNested(?Nested $nested): self
    {
        $this->nested = $nested;

        return $this;
    }

    public function setTerms(?Terms $terms): self
    {
        $this->terms = $terms;

        return $this;
    }

    public function setStats(?Stats $stats): self
    {
        $this->stats = $stats;

        return $this;
    }

    public function getKey(): string
    {
        return $this->key;
    }

    public function es(): array
    {
        $agg = [];

        if ($this->aggs) {
            $agg['aggs'] = array_merge($agg, $this->aggs->es()['aggs']);
        }

        if ($this->query && false === $this->query->isEmpty()) {
            $agg['filter'] = $this->query->es()[$this->query->getType()];
        }

        if ($this->nested) {
            $agg['nested'] = $this->nested->es()['nested'];
        }

        if ($this->terms) {
            $agg['terms'] = $this->terms->es()['terms'];
        }

        if ($this->stats) {
            $agg['stats'] = $this->stats->es()['stats'];
        }

        return $agg;
    }
}