<?php

declare(strict_types=1);

namespace apexl\Io\modules\cron\Trigger;

use DateInterval;
use DateTimeImmutable;
use Symfony\Component\Scheduler\Trigger\TriggerInterface;

/**
 * Trigger that fires the next iteration as soon as the previous one finishes,
 * with a minimum gap between starts to avoid pegging a CPU when the action is a
 * no-op or fails fast.
 *
 * Because the Scheduler runs handlers synchronously in-process, the next call
 * to getNextRunDate() always happens after the previous handler returned — so
 * returning ($lastRun + minimumGap) effectively means "go again now."
 */
final readonly class ContinuousTrigger implements TriggerInterface
{
    private DateInterval $minimumGap;

    public function __construct(int $minimumGapSeconds = 1)
    {
        $this->minimumGap = new DateInterval('PT' . max(1, $minimumGapSeconds) . 'S');
    }

    public function getNextRunDate(DateTimeImmutable $run): DateTimeImmutable
    {
        return $run->add($this->minimumGap);
    }

    public function __toString(): string
    {
        return 'continuous';
    }
}
