<?php

namespace IQDEV\ElasticSearch\Indexer;

use IQDEV\ElasticSearch\Configuration;
use IQDEV\ElasticSearch\Document\ProductDocument;
use IQDEV\ElasticSearch\Document\Property\Property;
use IQDEV\ElasticSearch\Document\Property\PropertyType;
use IQDEV\ElasticSearch\Facet\FacetFactory;

class BaseIndexProvider implements IndexProvider
{
    private ?int $size = null;
    private ?int $limit = null;

    public function __construct(
        private array $products,
        private Configuration $configuration
    ) {
    }

    public function get(): \Generator
    {
        foreach ($this->products as $product) {
            $document = new ProductDocument(
                FacetFactory::createFromProperty(new Property('category_id', PropertyType::BASE), $product['category'])
            );

            $document->setAdditionData($product['data'] ?? []);
            foreach ($product['properties'] as $type => $values) {
                foreach ($values as $key => $value) {
                    if ($type === 'number') {
                        $document->getNumberFacets()->add(
                            FacetFactory::createFromProperty(new Property($key, PropertyType::NUMBER), $value)
                        );
                    } else {
                        $document->getKeywordFacets()->add(
                            FacetFactory::createFromProperty(new Property($key, PropertyType::KEYWORD), $value)
                        );
                    }
                }
            }
            $document->setSearchContent($product['name']);

            yield new AddIndex(
                $this->configuration->getIndexName(),
                $document,
                $product['id']
            );
        }
    }

    public function setBatchSize(int $size): void
    {
        $this->size = $size;
    }

    public function getBatchSize(): ?int
    {
        return $this->size;
    }

    public function setLimit(int $limit): void
    {
        $this->limit = $limit;
    }

    public function getLimit(): ?int
    {
        return $this->limit;
    }
}