<?php
declare(strict_types=1);

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

final class EventCompactionArchive
{
    public function __construct(
        private readonly string $archiveId,
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly array $events = [],
        private readonly int $archivedCount = 0,
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $aggregateId, string $aggregateType, array $events): self
    {
        return new self(
            'archive_' . substr(hash('sha256', $aggregateId . $aggregateType . count($events)), 0, 24),
            $aggregateId,
            $aggregateType,
            $events,
            count($events),
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['archiveId'] ?? ''),
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (array) ($data['events'] ?? []),
            (int) ($data['archivedCount'] ?? 0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function archiveId(): string { return $this->archiveId; }
    public function archivedCount(): int { return max(0, $this->archivedCount); }

    public function toArray(): array
    {
        return [
            'archiveId' => $this->archiveId,
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'events' => $this->events,
            'archivedCount' => $this->archivedCount(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
