<?php

namespace App\Controller\OgBoot\OgLive;

use App\Controller\OgBoot\AbstractOgBootController;
use App\Entity\OgLive;
use App\Model\CommandTypes;
use App\Model\OgLiveStatus;
use App\Model\TraceStatus;
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 InstallAction extends AbstractOgBootController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(OgLive $data): JsonResponse
    {
        if (!$data->getDownloadUrl()) {
            throw new BadRequestHttpException('Download URL is required');
        }

        $params = [
            'json' => [
                'url' => $data->getDownloadUrl(),
                'id' => $data->getUuid()
            ]
        ];

        $inputData= [
            'downloadUrl' => $data->getDownloadUrl(),
            'uuid' => 'InstallOgLive_'.$data->getUuid()
        ];

        $content = $this->createRequest('POST', '/ogboot/v1/oglives/install', $params);

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

        $this->createService->__invoke(null, CommandTypes::INSTALL_OGLIVE, TraceStatus::IN_PROGRESS, 'InstallOgLive_'.$data->getUuid(), $inputData);

        $data->setName($this->simplifyOgLiveFilenameService->__invoke($data->getFilename()) ?? 'OgLive_'.$data->getUuid());
        $data->setDate(new \DateTime());
        $data->setStatus(OgLiveStatus::PENDING);
        $this->entityManager->persist($data);
        $this->entityManager->flush();

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