<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Hook;

use InPost\International\Hook\Event\HookInterface;
use InPost\International\Hook\Event\ParametersUpdatingHookInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class HookDispatcher implements HookDispatcherInterface
{
    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * @var HookEventFactoryInterface
     */
    private $eventFactory;

    public function __construct(EventDispatcherInterface $dispatcher, HookEventFactoryInterface $eventFactory)
    {
        $this->dispatcher = $dispatcher;
        $this->eventFactory = $eventFactory;
    }

    /**
     * {@inheritDoc}
     */
    public function dispatch(string $name, array $parameters)
    {
        $event = $this->eventFactory->create($name, $parameters);

        try {
            $this->dispatcher->dispatch($event, $event->getName());

            return $event->getResult();
        } finally {
            $this->updateParameters($parameters, $event);
        }
    }

    private function updateParameters(array $parameters, HookInterface $event): void
    {
        if (!$event instanceof ParametersUpdatingHookInterface) {
            return;
        }

        $event->updateParameters($parameters);
    }
}
