<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\DeployImageInput;
use App\Entity\Image;
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;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsController]
class RecoverAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(ImageImageRepository $data, HttpClientInterface $httpClient): JsonResponse
    {
        if (!$data->getImageFullsum()) {
            throw new BadRequestHttpException('Fullsum is required');
        }

        $image = $data->getImage();

        $params = [
            'json' => [
                'ID_img' => $data->getImageFullsum()
            ]
        ];

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

        $repository = $data->getRepository();

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

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

        $this->logger->info('Image recovered successfully', ['image' => $image->getName()]);

        $data->setStatus(ImageStatus::SUCCESS);
        $this->entityManager->persist($data);
        $this->entityManager->flush();

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