<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Dto\Output\CommandTaskScriptOutput;
use App\Entity\CommandTaskScript;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final readonly class CommandTaskScriptSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager,
    )
    {

    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['updateCommandTaskNextExecution', EventPriorities::POST_WRITE],
        ];
    }

    /**
     * @throws \Exception
     */
    public function updateCommandTaskNextExecution(ViewEvent $event): void
    {
        $commandTaskScriptOutput = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$commandTaskScriptOutput instanceof CommandTaskScriptOutput ||
            !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE])) {
            return;
        }

        /** @var CommandTaskScript $commandTaskScript */
        $commandTaskScript = $commandTaskScriptOutput->getEntity();

        $commandTask = $commandTaskScript->getCommandTask();

        if ($commandTask === null) {
            return;
        }

        $commandTask->setNextExecution($commandTask->calculateNextExecutionDate());

        $this->entityManager->persist($commandTask);
        $this->entityManager->flush();
    }

}