<?php

declare(strict_types=1);

namespace apexl\Io\modules\cron\Collection;

use apexl\Io\modules\cron\Interface\CronAction;
use Arrayy\Collection\AbstractCollection;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\Trigger\StaticMessageProvider;
use Symfony\Component\Scheduler\Trigger\TriggerInterface;

class ScheduleCollection extends AbstractCollection
{
    public function getType(): string
    {
        return Schedule::class;
    }

    /**
     * Build and register a Schedule for the given CronAction.
     *
     * Wraps the action in a StaticMessageProvider so RecurringMessage::trigger()
     * skips its serialize($message) call — necessary because Symfony Scheduler
     * was designed around plain-DTO messages, but a CronAction with DI-injected
     * services transitively holds non-serialisable resources (e.g. PDOStatement).
     *
     * Returns the built Schedule so callers can chain further configuration like
     * ->stateful($cache) or ->processOnlyLastMissedRun(true).
     */
    public function addAction(TriggerInterface $trigger, CronAction $action): Schedule
    {
        $schedule = (new Schedule())->with(
            RecurringMessage::trigger(
                $trigger,
                new StaticMessageProvider(
                    [$action],
                    id: hash('xxh128', $action::class),
                    description: $action::class,
                ),
            ),
        );

        $this->add($schedule, $action::class);

        return $schedule;
    }
}
