<?php
declare(strict_types=1);

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

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

final class DistributedQueueBalancer
{
    public function __construct(private readonly DistributedQueueCoordinator $queues) {}

    public function rebalance(): array
    {
        $summary = $this->queues->summary();
        $queues = $summary['queues'];

        if (count($queues) < 2) {
            return [
                'balanced' => true,
                'moves' => 0,
                'reason' => 'not enough queues to rebalance',
            ];
        }

        usort($queues, static fn (array $a, array $b): int => ((int) ($b['pending'] ?? 0)) <=> ((int) ($a['pending'] ?? 0)));

        $high = $queues[0];
        $low = $queues[count($queues) - 1];

        $difference = (int) ($high['pending'] ?? 0) - (int) ($low['pending'] ?? 0);
        $moves = $difference > 1 ? intdiv($difference, 2) : 0;

        return [
            'balanced' => true,
            'moves' => $moves,
            'from' => $high['queueName'] ?? '',
            'to' => $low['queueName'] ?? '',
        ];
    }
}
