<?php

declare(strict_types=1);

namespace KupShop\GraphQLBundle\ApiShared\Util;

use KupShop\CatalogBundle\ProductList\MultiFetch;
use KupShop\CatalogBundle\ProductList\ProductList;
use KupShop\CatalogBundle\Util\ProductsFilterSpecs;
use Query\Operator;

class ProductListUtil
{
    public function __construct(
        private readonly ProductList $productList,
        private readonly MultiFetch $multiFetch,
        private readonly GraphQLUtil $graphQLUtil,
        private readonly ProductsFilterSpecs $productsFilterSpecs,
    ) {
    }

    public function getProductList(): ProductList
    {
        // hack: kdyz nacitam produkty, tak tam nechci aplikovat logiku skrytí nepřeložených položek
        // tak to tady proste v configu vypnu
        $dbcfg = \Settings::getDefault();
        $dbcfg->hide_not_translated_objects = [];

        return clone $this->productList;
    }

    public function getProductsFilterSpecs(array $filterValues): ?callable
    {
        $specs = [];

        // hodnoty, ktere budou poslany do ProductsFilterSpecs, aby se z toho vygenerovaly specky pro filtr
        $filter = [];

        if ($filterValues['id'] ?? false) {
            $filter['products'] = (array) $filterValues['id'];
        }

        if ($filterValues['code'] ?? false) {
            $specs[] = Operator::inStringArray((array) $filterValues['code'], 'p.code');
        }

        if ($filterValues['ean'] ?? false) {
            $specs[] = Operator::inIntArray((array) $filterValues['ean'], 'p.ean');
        }

        if ($filterValues['producer'] ?? false) {
            $filter['producers'] = (array) $filterValues['producer'];
        }

        if ($filterValues['section'] ?? false) {
            $filter['categories'] = $filterValues['section'];
        }

        if ($filterValues['sectionRecursive'] ?? false) {
            $filter['categories_recursive'] = $filterValues['sectionRecursive'];
        }

        return $this->productsFilterSpecs->getSpecs($filter, $specs);
    }
}
