<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\Events;

use App\Framework\LiveComponents\ValueObjects\ComponentId;

/**
 * Domain event dispatched when a LiveComponent's state is updated
 *
 * This event is broadcast through the EventDispatcher and can be caught
 * by the SSE system to push real-time updates to connected clients.
 */
final readonly class ComponentUpdatedEvent
{
    /**
     * @param array<string, mixed> $state New component state
     * @param string|null $html Rendered HTML if available
     * @param array<ComponentEvent> $events Events emitted during update
     */
    public function __construct(
        public ComponentId $componentId,
        public array $state,
        public ?string $html = null,
        public array $events = []
    ) {
    }

    /**
     * Check if HTML was rendered
     */
    public function hasHtml(): bool
    {
        return $this->html !== null;
    }

    /**
     * Check if events were emitted
     */
    public function hasEvents(): bool
    {
        return ! empty($this->events);
    }

    /**
     * Get component ID as string
     */
    public function getComponentIdString(): string
    {
        return $this->componentId->toString();
    }

    /**
     * Convert to array for serialization
     */
    public function toArray(): array
    {
        return [
            'componentId' => $this->componentId->toString(),
            'state' => $this->state,
            'html' => $this->html,
            'events' => array_map(fn ($event) => $event->toArray(), $this->events),
        ];
    }
}
