<?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\EventDispatcher\Adapter;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface as EventDispatcherComponent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

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

if (!class_exists(Event::class)) {
    throw new \LogicException(sprintf('You cannot use the "%s" because the "symfony/event-dispatcher" package already fulfills the "%s" contract. Use "%s" directly instead.', EventDispatcher::class, EventDispatcherInterface::class, \Symfony\Component\EventDispatcher\EventDispatcher::class));
}

/**
 * @internal
 */
final class EventDispatcher implements EventDispatcherInterface
{
    /**
     * @var EventDispatcherComponent
     */
    private $dispatcher;

    public function __construct(EventDispatcherComponent $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @template T of Event
     *
     * @param T $event
     *
     * @return T the passed event
     */
    public function dispatch($event, string $eventName = null): object
    {
        if (!$event instanceof Event) {
            throw new \InvalidArgumentException(sprintf('Expected event to be an instance of "%s", "%s" given.', Event::class, get_debug_type($event)));
        }

        /* @phpstan-ignore argument.type, argument.type */
        return $this->dispatcher->dispatch($eventName ?? get_class($event), $event);
    }

    /**
     * Propagates calls to the inner dispatcher.
     */
    public function __call(string $name, array $arguments)
    {
        return $this->dispatcher->$name(...$arguments);
    }
}
