<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Queue\DeferredQueueManager;
use PpPhp\Core\Platform\Event\Scheduler\ScheduledEvent;
use PpPhp\Core\Platform\Event\Scheduler\SchedulerClock;
use PpPhp\Core\Platform\Event\Scheduler\ScheduleState;

final class SchedulerExecutor
{
    public function __construct(
        private readonly DeferredQueueManager $queue,
        private readonly SchedulerClock $clock = new SchedulerClock()
    ) {}

    public function execute(ScheduledEvent $event): ScheduledEvent
    {
        $this->queue->driver()->enqueue($event->toDeferredEvent());

        if ($event->recurring()) {
            return $event->reschedule($this->clock);
        }

        return $event->withState(ScheduleState::COMPLETED);
    }
}
