<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Console\Commands;

use PpPhp\Core\Platform\Console\AbstractCommand;

final class DistributedSchedulerDispatchCommand extends AbstractCommand
{
    public function name(): string { return 'distributed:scheduler:dispatch'; }
    public function description(): string { return 'PPphp Distributed Scheduler Dispatch'; }

    public function handle(array $arguments = []): int
    {
        $this->title('PPphp Distributed Scheduler Dispatch');

        $base = \PpPhp\Core\Platform\Console\ConsolePath::basePath();
        $runtime = \PpPhp\Core\Platform\Event\Distributed\DistributedRuntimeCoordinator::instance($base);

        if ($runtime->registry()->count() === 0) {
            $runtime->registerWorker('distributed_console_worker', 'console_node', 1);
        }

        $queues = \PpPhp\Core\Platform\Event\Distributed\Queue\DistributedQueueCoordinator::instance($base);

        if ($queues->registry()->get('console.scheduler') === null) {
            $queues->registerQueue('console.scheduler', 1);
        }

        $job = \PpPhp\Core\Platform\Event\Distributed\Scheduler\DistributedScheduleJob::create('console.scheduler.job.' . time(), 'console.scheduler', 1);
        $assignment = \PpPhp\Core\Platform\Event\Distributed\Scheduler\DistributedScheduler::instance($base)->schedule($job);

        $this->line('Assigned: ' . ($assignment->isAssigned() ? 'YES' : 'NO'));

        return 0;
    }
}
