<?php

declare(strict_types=1);

namespace MonsieurBiz\SyliusSearchPlugin\Factory\GridConfig;

use MonsieurBiz\SyliusSearchPlugin\Model\Config\GridConfig;
use MonsieurBiz\SyliusSearchPlugin\Model\Config\GridConfigInterface;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Product\Model\ProductAttributeInterface;
use Sylius\Component\Product\Model\ProductOption;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\HttpFoundation\Request;

class GridConfigFactory implements GridConfigFactoryInterface
{
    public function __construct(
        private readonly RepositoryInterface $productAttributeRepository,
        private readonly RepositoryInterface $productOptionRepository,
        private readonly array $gridConfig,
    ) {
    }

    public function create(
        string $type,
        Request $request,
        ?TaxonInterface $taxon = null,
        array $gridConfig = [],
    ): GridConfigInterface {
        $filters = array_merge($this->getAttributeFilters(), $this->getOptionFilters());

        $config = \count($gridConfig) > 0 ? $gridConfig : $this->gridConfig;

        $gridConfig = new GridConfig($config, $filters);
        $gridConfig->init($type, $request, $taxon);

        return $gridConfig;
    }

    private function getAttributeFilters(): array
    {
        $productAttributes = $this->productAttributeRepository->findBy([
            'filterable' => true,
        ]);

        $attributes = [];
        /** @var ProductAttributeInterface $attribute */
        foreach ($productAttributes as $attribute) {
            $attributes[] = $attribute->getCode();
        }

        return $attributes;
    }

    private function getOptionFilters(): array
    {
        $productOptions = $this->productOptionRepository->findBy([
            'filterable' => true,
        ]);

        $options = [];
        /** @var ProductOption $option */
        foreach ($productOptions as $option) {
            $options[] = $option->getCode();
        }

        return $options;
    }
}
