<?php

namespace App\Controller;

use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Dto\Input\ChangeOrganizationalUnitInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
use App\Repository\ClientRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

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()?->getTemplate();

            if (!$template) {
                throw new BadRequestHttpException('No template found for client');
            }

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

        $this->entityManager->flush();

        return new JsonResponse( data: 'Clients updated successfully', status: Response::HTTP_OK);
    }
}