<?php
declare(strict_types=1);

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

final class AggregateSnapshot
{
    public function __construct(
        private readonly string $snapshotId,
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly int $version,
        private readonly array $state = [],
        private readonly array $metadata = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $aggregateId,
        string $aggregateType,
        int $version,
        array $state = [],
        array $metadata = []
    ): self {
        return new self(
            'snap_' . substr(hash('sha256', $aggregateId . $aggregateType . $version), 0, 24),
            $aggregateId,
            $aggregateType,
            max(0, $version),
            $state,
            $metadata,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['snapshotId'] ?? ''),
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (int) ($data['version'] ?? 0),
            (array) ($data['state'] ?? []),
            (array) ($data['metadata'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function snapshotId(): string { return $this->snapshotId; }
    public function aggregateId(): string { return $this->aggregateId; }
    public function aggregateType(): string { return $this->aggregateType; }
    public function version(): int { return max(0, $this->version); }
    public function state(): array { return $this->state; }

    public function toArray(): array
    {
        return [
            'snapshotId' => $this->snapshotId,
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'version' => $this->version(),
            'state' => $this->state,
            'metadata' => $this->metadata,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
