<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\ValueObjects;

final readonly class LiveComponentState
{
    public function __construct(
        public string $id,
        public string $component,
        public array $data,
        public int $version = 1
    ) {
    }

    /**
     * Convert to array for JSON serialization (prevents double-encoding)
     */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'component' => $this->component,
            'data' => $this->data,
            'version' => $this->version,
        ];
    }

    /**
     * Convert to JSON string (for storage/transmission)
     */
    public function toJson(): string
    {
        return json_encode($this->toArray(), JSON_THROW_ON_ERROR);
    }

    public static function fromJson(string $json): self
    {
        $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

        return new self(
            id: $data['id'] ?? '',
            component: $data['component'] ?? '',
            data: $data['data'] ?? [],
            version: $data['version'] ?? 1
        );
    }

    public function withData(array $data): self
    {
        return new self(
            id: $this->id,
            component: $this->component,
            data: $data,
            version: $this->version + 1
        );
    }
}
