<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed\Failover;

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

final class DistributedLeaseRecoveryManager
{
    public function __construct(
        private readonly DistributedLeaseManager $leases,
        private readonly DistributedFailoverPolicy $policy = new DistributedFailoverPolicy()
    ) {}

    public function recover(array $failedNodeIds): DistributedLeaseRecoveryResult
    {
        $expired = $this->policy->recoverExpiredLeases() ? $this->leases->expireDue() : 0;
        $affected = [];
        $recovered = 0;

        foreach ($this->leases->collection()->toArray() as $lease) {
            if (!in_array((string) ($lease['nodeId'] ?? ''), $failedNodeIds, true)) {
                continue;
            }

            if (($lease['status'] ?? '') === 'active' || ($lease['expired'] ?? false) === true) {
                $affected[] = $lease;
                $recovered++;
            }
        }

        return new DistributedLeaseRecoveryResult($expired, $recovered, $affected);
    }
}
