<?php
declare(strict_types=1);

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

final class DomainEventCheckpoint
{
    public function __construct(
        private readonly int $lastSequence = 0,
        private readonly int $processed = 0,
        private readonly string $updatedAt = ''
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            (int) ($data['lastSequence'] ?? 0),
            (int) ($data['processed'] ?? 0),
            (string) ($data['updatedAt'] ?? '')
        );
    }

    public function lastSequence(): int { return max(0, $this->lastSequence); }
    public function processed(): int { return max(0, $this->processed); }

    public function advance(int $sequence): self
    {
        return new self(max($this->lastSequence(), $sequence), $this->processed() + 1, date('c'));
    }

    public function reset(): self
    {
        return new self(0, 0, date('c'));
    }

    public function toArray(): array
    {
        return [
            'lastSequence' => $this->lastSequence(),
            'processed' => $this->processed(),
            'updatedAt' => $this->updatedAt !== '' ? $this->updatedAt : date('c'),
        ];
    }
}
