<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\BackupImageInput;
use App\Dto\Input\ConvertImageToVirtualInput;
use App\Entity\ImageImageRepository;
use App\Model\CommandTypes;
use App\Model\ImageStatus;
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;

#[AsController]
class ConvertImageToVirtualAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(ConvertImageToVirtualInput $input, ImageImageRepository $imageImageRepository): JsonResponse
    {
        $image = $imageImageRepository->getImage();

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

        $params = [
            'json' => [
                'ID_img' => $imageImageRepository->getImageFullsum(),
                'vm_extension' => $input->extension,
            ]
        ];

        $this->logger->info('Convert image to virtual', ['image' => $image->getName()]);

        $repository = $imageImageRepository->getRepository();

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

        if (isset($content['error']) && $content['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new BadRequestHttpException('An error occurred while converting the image to virtual: ' . $content['error']);
        }

        $inputData = [
            'imageName' => $image->getName(),
            'repositoryUuid' => $repository->getUuid(),
            'imageImageRepositoryUuid' => $imageImageRepository->getUuid(),
            'ID_img' => $imageImageRepository->getImageFullsum(),
        ];

        $this->createService->__invoke($image->getClient(), CommandTypes::CONVERT_IMAGE_TO_VIRTUAL, TraceStatus::IN_PROGRESS, $content['job_id'], $inputData);

        $imageImageRepository->setStatus(ImageStatus::TRANSFERRING);
        $this->entityManager->persist($imageImageRepository);
        $this->entityManager->flush();

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