<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Lifecycle;

use PpPhp\Core\Platform\Event\EventBus;

final class LifecycleEventPublisher
{
    public function __construct(private readonly EventBus $bus) {}

    public function publish(LifecycleEvent $event): array
    {
        return $this->bus->dispatch($event)->toArray();
    }

    public function publishByName(string $eventName, array $payload = [], array $metadata = []): ?array
    {
        $entry = LifecycleEventManifest::registry()->get($eventName);

        if (!$entry || !class_exists($entry['class'])) {
            return null;
        }

        $className = $entry['class'];
        $event = new $className($payload, $metadata);

        return $this->publish($event);
    }
}
