<?php

declare(strict_types=1);

namespace External\HannahBundle\EventSubscriber\Catalog;

use External\HannahBundle\Util\Configuration;
use External\HannahBundle\Util\Product\ProductRelatedVariationsUtil;
use KupShop\CatalogBundle\Event\CatalogEvent;
use KupShop\CatalogBundle\ProductList\ProductCollection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CatalogSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly Configuration $configuration,
        private readonly ProductRelatedVariationsUtil $productRelatedVariationsUtil,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CatalogEvent::class => [
                ['fetchRelatedVariationIds', 200],
            ],
        ];
    }

    /**
     * Pokud se na katalogu zafiltruje podle varianty, tak se provedou multifetche pro nacteni `relatedVariationId`, ktera se nasledne
     * strci v sablonach jako soucast odkazu.
     */
    public function fetchRelatedVariationIds(CatalogEvent $event): void
    {
        if ($this->configuration->getShopId() !== Configuration::SHOP_ROCKPOINT) {
            return;
        }

        if ($event->type !== CatalogEvent::TYPE_CATEGORY) {
            return;
        }

        $event->productList->addResultModifiers(function (ProductCollection $products) use ($event) {
            $this->productRelatedVariationsUtil->fetchProductsRelatedVariationIdByFilterParams($products, $event->filterParams);
        });
    }
}
