<?php

declare(strict_types=1);

namespace External\ZNZBundle\Util\Product;

use External\ZNZBundle\Util\ZNZConfiguration;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\PricelistBundle\Context\PricelistContext;
use KupShop\PricelistBundle\Query\Product;
use Query\Operator;
use Query\QueryBuilder;

class ZNZProductRestrictions
{
    public function __construct(private ZNZConfiguration $configuration)
    {
    }

    public function getSpec(): ?callable
    {
        $specs = [];

        foreach (get_class_methods($this) as $method) {
            if (!str_starts_with($method, 'getSpec_')) {
                continue;
            }

            $specs[] = $this->$method();
        }

        return Operator::andX($specs);
    }

    /**
     * V pripade B2B modu zobrazujeme jen produkty, u kterych je vyplnena cena v ceniku, ktery maji aktivni.
     *
     * Neprihlasenum uzivatleum se zobrazuji vsechny produkty, ale prihlasenemu B2B zobrazujeme uz jen jeho sortiment.
     */
    private function getSpec_B2BPriceRestriction(): ?callable
    {
        if (!$this->configuration->isB2BShop()) {
            return null;
        }

        if (!($priceListId = Contexts::get(PriceListContext::class)->getActiveId())) {
            return null;
        }

        return function (QueryBuilder $qb) use ($priceListId) {
            $qb->joinVariationsOnProducts();
            $qb->andWhere(Product::applyPricelist($priceListId));

            $priceField = 'COALESCE(prlv.price, prlp.price)';

            return "{$priceField} IS NOT NULL AND {$priceField} > 0";
        };
    }
}
