<?php

namespace App\Controller;

use App\Dto\Input\CommandExecuteInput;
use App\Dto\Input\CommandGroupAddCommandsInput;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\CommandGroup;
use App\Entity\Trace;
use App\Model\TraceStatus;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class CommandExecuteAction extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager
    )
    {
    }

    public function __invoke(CommandExecuteInput $input, Command $command): JsonResponse
    {
        $clients = $input->clients;

        /** @var Client $client */
        foreach ($clients as $client) {
            $trace = new Trace();
            $trace->setClient($client->getEntity());
            $trace->setCommand($command);
            $trace->setStatus(TraceStatus::IN_PROGRESS);
            $trace->setExecutedAt(new \DateTimeImmutable());

            $this->entityManager->persist($trace);
        }

        $this->entityManager->flush();

        return new JsonResponse(data: 'Command executed successfully', status: Response::HTTP_OK);
    }
}