<?php

namespace App\Controller\OgBoot\PxeTemplate;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Controller\OgDhcp\AbstractOgDhcpController;
use App\Dto\Input\PxeTemplateAddClientsInput;
use App\Entity\Client;
use App\Entity\PxeTemplate;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsController]
class AddClientAction extends AbstractController
{
    public function __construct(
        private readonly \App\Controller\OgBoot\PxeBootFile\PostAction $postAction,
        private readonly EntityManagerInterface $entityManager,
    )
    {

    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(PxeTemplateAddClientsInput $input, PxeTemplate $pxeTemplate): JsonResponse
    {
        $clients = $input->clients;

        foreach ($clients as $client) {
            $this->postAction->__invoke($client->getEntity(), $pxeTemplate);

            /** @var Client $clientEntity */
            $clientEntity = $client->getEntity();
            $clientEntity->setTemplate($pxeTemplate);

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

        $this->entityManager->flush();

        return new JsonResponse(status: Response::HTTP_OK);
    }
}