<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

use App\Dto\Input\DeployImageInput;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\Partition;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\DeployMethodTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
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;

class DeployImageAction extends AbstractOgAgentController
{
    /**
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     */
    public function __invoke(ImageImageRepository $imageImageRepository, DeployImageInput $input, Client $client, ?string $method = null)
    {
        $image = $imageImageRepository->getImage();

        if (!$client->getIp()) {
            throw new BadRequestHttpException('IP is required');
        }

        if ($input->type === 'git') {
            throw new BadRequestHttpException('Use DeployGitImageAction for Git images');
        }

        $method = match ($input->method) {
            DeployMethodTypes::MULTICAST_UFTP_DIRECT, DeployMethodTypes::MULTICAST_UDPCAST_DIRECT, => 'multicast-direct',
            DeployMethodTypes::MULTICAST, DeployMethodTypes::MULTICAST_UFTP, DeployMethodTypes::MULTICAST_UDPCAST => 'multicast',
            DeployMethodTypes::UNICAST_DIRECT => 'unicast-direct',
            DeployMethodTypes::UNICAST => 'unicast',
            DeployMethodTypes::TORRENT => 'torrent',
            default => throw new BadRequestHttpException('Invalid method'),
        };

        $mcastMode = $input->mcastMode.'-duplex';
        $mcastSpeed = $input->mcastSpeed.'M';

        $ptcMulticastValue = "$method $input->mcastPort:$mcastMode:$input->mcastIp:$mcastSpeed:$input->maxClients:$input->maxTime";
        $ptcTorrentValue = "$method $input->p2pMode:$input->p2pTime";
        $ptcUnicastValue = $method;

        $ptcValue = match ($input->method) {
            DeployMethodTypes::MULTICAST, DeployMethodTypes::MULTICAST_UFTP, DeployMethodTypes::MULTICAST_UFTP_DIRECT, DeployMethodTypes::MULTICAST_UDPCAST, DeployMethodTypes::MULTICAST_UDPCAST_DIRECT => $ptcMulticastValue,
            DeployMethodTypes::UNICAST, DeployMethodTypes::UNICAST_DIRECT => $ptcUnicastValue,
            DeployMethodTypes::TORRENT => $ptcTorrentValue,
            default => throw new BadRequestHttpException('Invalid method'),
        };

        $repository = $imageImageRepository->getRepository();

        $data = [
            'dsk' => (string) $input->diskNumber,
            'par' => (string) $input->partitionNumber,
            'ifs' => "1",
            'idi' => $image->getUuid(),
            'nci' => $imageImageRepository->getName(),
            'ipr' => $repository->getIp(),
            'nfn' => 'RestaurarImagen',
            'ptc' => $ptcValue,
            'ids' => '0'
        ];

        $url = 'https://'.$client->getIp().':8000/opengnsys/RestaurarImagen';

        $response = $this->createRequest(
            method: 'POST',
            url: $url,
            params: [
                'json' => $data,
            ],
            token: $client->getToken(),
        );

        $this->logger->info('Deploying image', [ 
            'image' => $imageImageRepository->getName(), 
            'repository' => $repository->getIp(),
            'client' => $client->getIp()
        ]);

        if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new BadRequestHttpException('Error deploying image');
        }

        $jobId = $response['job_id'];

        $client->setStatus(ClientStatus::BUSY);
        $this->entityManager->persist($client);
        $this->entityManager->flush();

        return $jobId;
    }
}
