<?php

namespace App\Controller\OgBoot\PxeTemplate;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Entity\PxeTemplate;
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 GetAction extends AbstractOgBootController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(PxeTemplate $template, HttpClientInterface $httpClient): JsonResponse
    {
        $response = $this->createRequest('GET', '/ogboot/v1/pxe-templates/'.$template->getName());

        if ($response->getStatusCode() !== Response::HTTP_OK) {
            return new JsonResponse( data: 'An error occurred', status: Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        $data = json_decode($response->getContent(), true);

        $template->setName($data['template_name']);
        $template->setTemplateContent($data['template_content']);
        $template->setSynchronized(true);

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

        return new JsonResponse( data: $data, status: Response::HTTP_OK);
    }
}