<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed\Lease\Validation;

use PpPhp\Core\Platform\Event\Distributed\Lease\DistributedLeaseManager;

final class DistributedLeaseVerifier
{
    public function verify(string $basePath): array
    {
        $manager = DistributedLeaseManager::resetInstance($basePath);
        $manager->clear();

        $lease = $manager->acquire('job_verify_1', 'node_verify_a', 'worker_verify_a', 60);
        $conflict = $manager->acquire('job_verify_1', 'node_verify_b', 'worker_verify_b', 60);
        $renewed = $lease !== null ? $manager->renew($lease->leaseId(), 120) : false;
        $released = $lease !== null ? $manager->release($lease->leaseId()) : false;

        $expiredLease = $manager->acquire('job_verify_expired', 'node_verify_a', 'worker_verify_a', 1);
        sleep(2);
        $expired = $manager->expireDue();

        $manager->save();

        $second = DistributedLeaseManager::resetInstance($basePath);
        $second->hydrate();

        $stats = $second->snapshot()->statistics();

        $checks = [
            'acquire' => $lease !== null,
            'conflict' => $conflict === null,
            'renew' => $renewed,
            'release' => $released,
            'expiry' => $expired >= 1,
            'persistence' => $second->store()->exists(),
            'hydration' => ($stats['leases'] ?? 0) >= 2,
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Distributed lease verification failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'leases' => $stats['leases'] ?? 0,
                'active' => $stats['active'] ?? 0,
                'released' => $stats['released'] ?? 0,
                'expired' => $stats['expired'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
