<?php

namespace App\Controller\OgBoot\OgLive;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Entity\OgLive;
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\HttpKernel\Exception\HttpException;
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 UninstallAction extends AbstractOgBootController
{
    /**
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws TransportExceptionInterface
     */
    public function __invoke(OgLive $data): JsonResponse
    {
        if (!$data->getChecksum()) {
            throw new BadRequestHttpException('Checksum is required');
        }

        $content = $this->createRequest( 'DELETE', '/ogboot/v1/oglives/'.$data->getChecksum());

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

        $this->entityManager->remove($data);
        $this->entityManager->flush();

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