<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Versioning;

final class EventVersion
{
    public function __construct(private readonly string $eventType, private readonly int $version = 1, private readonly string $schema = '', private readonly string $createdAt = '') {}

    public static function create(string $eventType, int $version = 1, string $schema = ''): self
    {
        return new self($eventType, max(1, $version), $schema, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self((string) ($data['eventType'] ?? ''), (int) ($data['version'] ?? 1), (string) ($data['schema'] ?? ''), (string) ($data['createdAt'] ?? ''));
    }

    public function eventType(): string { return $this->eventType; }
    public function version(): int { return max(1, $this->version); }

    public function toArray(): array
    {
        return ['eventType' => $this->eventType, 'version' => $this->version(), 'schema' => $this->schema, 'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c')];
    }
}
