<?php
declare(strict_types=1);

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

final class EventVersioningResult
{
    public function __construct(private readonly string $eventId, private readonly string $eventType, private readonly int $fromVersion, private readonly int $toVersion, private readonly bool $upcasted, private readonly array $event = [], private readonly string $createdAt = '') {}

    public static function create(array $event, int $fromVersion, int $toVersion, bool $upcasted): self
    {
        return new self((string) ($event['eventId'] ?? ''), (string) ($event['eventType'] ?? ''), $fromVersion, $toVersion, $upcasted, $event, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self((string) ($data['eventId'] ?? ''), (string) ($data['eventType'] ?? ''), (int) ($data['fromVersion'] ?? 1), (int) ($data['toVersion'] ?? 1), (bool) ($data['upcasted'] ?? false), (array) ($data['event'] ?? []), (string) ($data['createdAt'] ?? ''));
    }

    public function upcasted(): bool { return $this->upcasted; }
    public function event(): array { return $this->event; }

    public function toArray(): array
    {
        return ['eventId' => $this->eventId, 'eventType' => $this->eventType, 'fromVersion' => $this->fromVersion, 'toVersion' => $this->toVersion, 'upcasted' => $this->upcasted, 'event' => $this->event, 'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c')];
    }
}
