<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\DeleteImageInput;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\ImageRepository;
use App\Model\ImageStatus;
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 DeleteTrashAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(ImageImageRepository $imageImageRepository): JsonResponse
    {
        $repository = $imageImageRepository->getRepository();
        $image = $imageImageRepository->getImage();

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

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

        $content = $this->createRequest('DELETE', 'http://'.$repository->getIp().':8006/ogrepository/v1/images/'.$imageImageRepository->getImageFullsum().'?method=trash');

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

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

        $imageImageCollection = $image->getImageImageRepositories();

        if ($imageImageCollection->isEmpty()) {
            $this->entityManager->remove($image);
            $this->entityManager->flush();
        }

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