<?php

namespace App\Controller\OgBoot\PxeTemplate;

use App\Controller\OgBoot\AbstractOgBootController;
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\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Validator\Exception\ValidatorException;
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 DeleteAction extends AbstractOgBootController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(PxeTemplate $data): JsonResponse
    {
        $this->entityManager->remove($data);
        $this->entityManager->flush();

        $content = $this->createRequest('DELETE', '/ogboot/v1/pxe-templates/'.$data->getName());

        if (isset($content['error']) && $content['error'] === Response::HTTP_INTERNAL_SERVER_ERROR ) {
            throw new BadRequestHttpException('An error occurred: ' . $content['error']);
        }

        $defaultTemplateEntity = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['isDefault' => true]);

        if ($defaultTemplateEntity === null) {
            return new JsonResponse(
                'Default template not found',
                Response::HTTP_NOT_FOUND
            );
        }

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