<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Scheduler;

use DateInterval;
use DateTimeImmutable;

final class ScheduleExpression
{
    public function __construct(private readonly string $expression) {}

    public static function delaySeconds(int $seconds): self
    {
        return new self('PT' . max(0, $seconds) . 'S');
    }

    public static function afterResponse(): self
    {
        return new self('after-response');
    }

    public static function at(string $dateTime): self
    {
        return new self('at:' . $dateTime);
    }

    public static function every(string $interval): self
    {
        return new self('every:' . $interval);
    }

    public function value(): string
    {
        return $this->expression;
    }

    public function nextRunAt(SchedulerClock $clock): string
    {
        if ($this->expression === 'after-response') {
            return $clock->now()->format(DATE_ATOM);
        }

        if (str_starts_with($this->expression, 'at:')) {
            return substr($this->expression, 3);
        }

        if (str_starts_with($this->expression, 'every:')) {
            $interval = substr($this->expression, 6);
            return $clock->now()->add(new DateInterval($interval))->format(DATE_ATOM);
        }

        return $clock->now()->add(new DateInterval($this->expression))->format(DATE_ATOM);
    }
}
