<?php

namespace Myvetshop\Module\Clinique\Adapter;

use Myvetshop\Module\Clinique\Prestashop\Hook\ActionObjectCartUpdateBefore\ActionObjectCartUpdateBeforeInterface;
use Myvetshop\Module\Clinique\Prestashop\Hook\DisplayFooterProduct\DisplayFooterProductListenerInterface;
use Myvetshop\Module\Clinique\Prestashop\Hook\DisplayProductExtraContent\DisplayProductExtraContentInterface;
use Myvetshop\Module\Clinique\Prestashop\Hook\HookListenerInterface;

class PrestashopHookAdapter
{
    /**
     * @var list<HookListenerInterface>
     */
    private array $hookListeners;

    /**
     * @param iterable<HookListenerInterface> $hookListeners
     */
    public function __construct(iterable $hookListeners)
    {
        $this->hookListeners = \is_array($hookListeners)
            ? \array_values($hookListeners)
            : \iterator_to_array($hookListeners, false);
    }

    public function actionObjectCartUpdateBefore(\Cart $cart): void
    {
        foreach ($this->hookListeners as $hookListener) {
            if (!$hookListener instanceof ActionObjectCartUpdateBeforeInterface) {
                continue;
            }

            $hookListener->actionObjectCartUpdateBefore($cart);
        }
    }

    public function displayFooterProduct(\Category $category, \Product $product): string
    {
        return \array_reduce(
            $this->hookListeners,
            function (string $carry, HookListenerInterface $hookListener) use ($category, $product): string {
                if ($hookListener instanceof DisplayFooterProductListenerInterface) {
                    $carry .= $hookListener->displayFooterProduct($category, $product);
                }

                return $carry;
            },
            ''
        );
    }

    /**
     * @return \PrestaShop\PrestaShop\Core\Product\ProductExtraContent[]
     */
    public function displayProductExtraContent(\Product $product): array
    {
        return \array_reduce(
            $this->hookListeners,
            function (array $carry, HookListenerInterface $hookListener) use ($product): array {
                if ($hookListener instanceof DisplayProductExtraContentInterface) {
                    $carry += $hookListener->displayProductExtraContent($product);
                }

                return $carry;
            },
            []
        );
    }
}
