<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\DeployImageInput;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Model\CommandTypes;
use App\Model\DeployImageTypes;
use App\Model\DeployMethodTypes;
use App\Model\TraceStatus;
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 DeployImageAction extends AbstractOgRepositoryController
{
    /**
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws TransportExceptionInterface
     */
    public function __invoke(DeployImageInput $input, ImageImageRepository $data, Client $client): JsonResponse
    {
        $params = [
            'json' => [
                'ID_img' => $data->getImageFullsum(),
                //'image_name' => $data->getName(),
                'bitrate' => (string) $input->mcastSpeed.'M',
                'ip' => $input->mcastIp,
                'port' => $input->mcastPort,
                'method' => $input->mcastMode,
                'nclients' => $input->maxClients,
                'maxtime' => $input->maxTime
            ]
        ];

        $type = match ($input->method) {
            'udpcast', 'udpcast-direct' => DeployMethodTypes::MULTICAST_UDPCAST,
            'p2p' => DeployMethodTypes::TORRENT,
            default => null,
        };

        $repository = $client->getRepository();

        $content = $this->createRequest('POST', 'http://'.$repository->getIp().':8006/ogrepository/v1/'.$type, $params);

        // Verificar si la respuesta contiene un error HTTP 500
        if (isset($content['code']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new \Exception('Error del servidor OgRepository: ' . ($content['error'] ?? 'Error desconocido') . ' - ' . ($content['details'] ?? ''));
        }

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