<?php

namespace App\Controller\OgBoot\PxeTemplate;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Entity\OgLive;
use App\Entity\PxeTemplate;
use App\Model\OgLiveStatus;
use Doctrine\ORM\EntityManagerInterface;
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 SyncAction extends AbstractOgBootController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(): JsonResponse
    {
        $content = $this->createRequest('GET', '/ogboot/v1/pxe-templates');
        $templateNamesFromApi = $content['message'];

        $existingTemplates = $this->entityManager->getRepository(PxeTemplate::class)->findAll();

        $existingTemplateNames = array_map(fn($t) => $t->getName(), $existingTemplates);

        foreach ($existingTemplates as $existingTemplate) {
            if (!in_array($existingTemplate->getName(), $templateNamesFromApi, true)) {
                $this->entityManager->remove($existingTemplate);
            }
        }

        foreach ($templateNamesFromApi as $templateName) {
            $templateEntity = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['name' => $templateName]);

            if (!$templateEntity) {
                $templateEntity = new PxeTemplate();
                $templateEntity->setName($templateName);
            }

            $templateContent = $this->createRequest('GET', '/ogboot/v1/pxe-templates/' . $templateEntity->getName());

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

            $templateEntity->setTemplateContent($templateContent['template_content']);
            $templateEntity->setSynchronized(true);

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

        $this->entityManager->flush();

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