<?php
declare(strict_types=1);

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

final class EventSourcingRuntimeLock
{
    public function __construct(
        private readonly string $lockId,
        private readonly string $status,
        private readonly int $score,
        private readonly array $report = [],
        private readonly string $lockedAt = ''
    ) {}

    public static function create(EventSourcingRuntimeReport $report): self
    {
        return new self(
            'cqrs_lock_' . substr(hash('sha256', json_encode($report->toArray()) . date('c')), 0, 24),
            $report->passed() ? 'LOCKED' : 'UNLOCKED',
            $report->score(),
            $report->toArray(),
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['lockId'] ?? ''),
            (string) ($data['status'] ?? 'UNLOCKED'),
            (int) ($data['score'] ?? 0),
            (array) ($data['report'] ?? []),
            (string) ($data['lockedAt'] ?? '')
        );
    }

    public function status(): string { return $this->status; }
    public function score(): int { return $this->score; }
    public function locked(): bool { return $this->status === 'LOCKED' && $this->score === 100; }

    public function toArray(): array
    {
        return [
            'lockId' => $this->lockId,
            'status' => $this->status,
            'score' => $this->score,
            'report' => $this->report,
            'lockedAt' => $this->lockedAt !== '' ? $this->lockedAt : date('c'),
        ];
    }
}
