<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Distributed\Queue\DistributedQueueCoordinator;
use PpPhp\Core\Platform\Event\Distributed\Scheduler\DistributedQueueBalancer;

final class DistributedQueueRecoveryManager
{
    public function __construct(
        private readonly DistributedQueueCoordinator $queues,
        private readonly DistributedFailoverPolicy $policy = new DistributedFailoverPolicy()
    ) {}

    public function recover(): DistributedQueueRecoveryResult
    {
        if (!$this->policy->rebalanceQueues()) {
            return new DistributedQueueRecoveryResult(true, 0, ['reason' => 'queue rebalance disabled']);
        }

        $result = (new DistributedQueueBalancer($this->queues))->rebalance();

        return new DistributedQueueRecoveryResult(
            (bool) ($result['balanced'] ?? true),
            (int) ($result['moves'] ?? 0),
            $result
        );
    }
}
