<?php

namespace App\Service;

use App\Entity\CommandTask;
use App\Entity\Trace;
use App\Model\TraceStatus;
use Doctrine\ORM\EntityManagerInterface;

readonly class CreateTraceService
{
    public function __construct(
        private EntityManagerInterface $entityManager
    )
    {
    }

    public function __invoke(CommandTask $commandTask): void
    {
        foreach ($commandTask->getCommands() as $command) {
            foreach ($commandTask->getClients() as $client) {
                $trace = new Trace();
                $trace->setClient($client);
                $trace->setCommand($command->getName());
                $trace->setStatus(TraceStatus::PENDING);
                $trace->setInput($commandTask->getParameters());
                $trace->setExecutedAt($commandTask->getDatetime());
                $this->entityManager->persist($trace);
            }
        }

        foreach ($commandTask->getCommandGroups() as $commandGroup) {
            foreach ($commandTask->getCommands() as $command) {
                foreach ($commandTask->getClients() as $client) {
                    $trace = new Trace();
                    $trace->setClient($client);
                    $trace->setCommand($command->getName());
                    $trace->setInput($commandTask->getParameters());
                    $trace->setStatus(TraceStatus::PENDING);
                    $trace->setExecutedAt($commandTask->getDatetime());
                    $this->entityManager->persist($trace);
                }
            }
        }

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