<?php

namespace App\Controller;

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

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

    public function __invoke(CommandGroupAddCommandsInput $input, CommandGroup $commandGroup): JsonResponse
    {
        $commands = $input->commands;

        /** @var Command $command */
        foreach ($commands as $command) {
            $commandGroup->addCommand($command->getEntity());
        }

        $this->entityManager->persist($commandGroup);
        $this->entityManager->flush();

        return new JsonResponse(data: 'Commands added to command group successfully', status: Response::HTTP_OK);
    }
}