<?php

declare(strict_types=1);

namespace App\Framework\Sse\Listeners;

use App\Framework\Core\Events\OnEvent;
use App\Framework\LiveComponents\Events\ComponentUpdatedEvent;
use App\Framework\Sse\SseBroadcaster;

/**
 * Event listener that automatically broadcasts LiveComponent events via SSE
 *
 * This service listens to domain events from the EventDispatcher
 * and broadcasts them to connected SSE clients in real-time.
 *
 * Uses attribute-based discovery for automatic registration.
 */
final readonly class SseEventBroadcaster
{
    public function __construct(
        private SseBroadcaster $broadcaster
    ) {}

    /**
     * Handle component update events
     *
     * Broadcasts component updates to all clients subscribed to the component's channel
     */
    #[OnEvent(priority: 100)]
    public function onComponentUpdated(ComponentUpdatedEvent $event): void
    {
        $this->broadcaster->broadcastComponentUpdate(
            componentId: $event->componentId,
            state: $event->state,
            html: $event->html ?? '',
            events: array_map(fn ($e) => $e->toArray(), $event->events)
        );
    }
}
