<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Entity\Client;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\Trace;
use App\Model\CommandTypes;
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\Component\HttpKernel\Exception\BadRequestHttpException;
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 CancelTransmissionAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(Trace $data): JsonResponse
    {
        if ($data->getCommand() !== CommandTypes::DEPLOY_IMAGE) {
            throw new BadRequestHttpException('Command is not DEPLOY_IMAGE');
        }

        $input = $data->getInput();

        if (!isset($input['client']) || !isset($input['image']) || !isset($input['method'])) {
            throw new BadRequestHttpException('Client, image and method are required');
        }
        $client = $this->entityManager->getRepository(Client::class)->findOneBy(['uuid' => $input['client']]);
        $image = $this->entityManager->getRepository(ImageImageRepository::class)->findOneBy(['uuid' => $input['image']]);

        if (!$client || !$image) {
            throw new BadRequestHttpException('Client or image not found');
        }

        $method = $input['method'];

        if (!$image->getImageFullsum()) {
            throw new BadRequestHttpException('Fullsum is required');
        }

        if ($method === DeployMethodTypes::TORRENT) {
            $content = $this->createRequest('DELETE', 'http://'.$image->getRepository()->getIp().':8006/ogrepository/v1/p2p');
        } else {
            $content = $this->createRequest('DELETE', 'http://'.$image->getRepository()->getIp().':8006/ogrepository/v1/'.$method.'/images/'.$image->getImageFullsum());
        }

        if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR ) {
            throw new BadRequestHttpException('Error cancelling transmission: ' . $content['details']);
        }

        $data->setStatus(TraceStatus::CANCELLED);
        $this->entityManager->persist($data);
        $this->entityManager->flush();

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