<?php
declare(strict_types=1);

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

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

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

    public function projectionId(): string { return $this->projectionId; }
    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(
            $this->projectionId,
            max($this->lastSequence(), $sequence),
            $this->processed() + 1,
            date('c')
        );
    }

    public function reset(): self
    {
        return new self($this->projectionId, 0, 0, date('c'));
    }

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