<?php
declare(strict_types=1);

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

final class EventCompactionResult
{
    public function __construct(
        private readonly string $resultId,
        private readonly string $aggregateId,
        private readonly string $aggregateType,
        private readonly int $beforeCount,
        private readonly int $afterCount,
        private readonly int $compactedCount,
        private readonly bool $archived,
        private readonly string $reason = '',
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $aggregateId,
        string $aggregateType,
        int $beforeCount,
        int $afterCount,
        bool $archived,
        string $reason = 'stream compacted'
    ): self {
        return new self(
            'compact_' . substr(hash('sha256', $aggregateId . $aggregateType . $beforeCount . $afterCount), 0, 24),
            $aggregateId,
            $aggregateType,
            $beforeCount,
            $afterCount,
            max(0, $beforeCount - $afterCount),
            $archived,
            $reason,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['resultId'] ?? ''),
            (string) ($data['aggregateId'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (int) ($data['beforeCount'] ?? 0),
            (int) ($data['afterCount'] ?? 0),
            (int) ($data['compactedCount'] ?? 0),
            (bool) ($data['archived'] ?? false),
            (string) ($data['reason'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

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

    public function toArray(): array
    {
        return [
            'resultId' => $this->resultId,
            'aggregateId' => $this->aggregateId,
            'aggregateType' => $this->aggregateType,
            'beforeCount' => $this->beforeCount,
            'afterCount' => $this->afterCount,
            'compactedCount' => $this->compactedCount(),
            'archived' => $this->archived,
            'reason' => $this->reason,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
