<?php

namespace App\Controller;

use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Dto\Input\ChangeOrganizationalUnitInput;
use App\Entity\Client;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
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\Component\HttpKernel\Exception\BadRequestHttpException;

class ChangeOrganizationalUnitAction extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private PostAction $postAction,
    )
    {
    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(ChangeOrganizationalUnitInput $input): JsonResponse
    {
        foreach ($input->clients as $client) {
            /** @var Client $clientEntity */
            $clientEntity = $client->getEntity();

            $organizationalUnit = $input->organizationalUnit->getEntity();
            $clientEntity->setOrganizationalUnit($organizationalUnit);

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

            $template = $clientEntity->getTemplate() ?? $clientEntity->getOrganizationalUnit()->getNetworkSettings()?->getPxeTemplate();

            if (!$template) {
                throw new BadRequestHttpException('No se han encontrado plantillas PXE asociadas al cliente o a la unidad organizativa.');
            }

            $this->postAction->__invoke($clientEntity, $template);
        }

        $this->entityManager->flush();

        return new JsonResponse( data: 'Clientes actualizados correctamente', status: Response::HTTP_OK);
    }
}