<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\ExportImportImageRepositoryInput;
use App\Dto\Input\TransferGlobalImageInput;
use App\Entity\Image;
use App\Entity\ImageImageRepository;
use App\Entity\ImageRepository;
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 TransferAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(TransferGlobalImageInput $input, ImageImageRepository $imageImageRepository): JsonResponse
    {
        $repositories = $input->repositories;

        foreach ($repositories as $repositoryEntity) {
            /** @var ImageRepository $repository */
            $repository = $repositoryEntity->getEntity();
            /* @var Image $image */
            $image = $imageImageRepository->getImage();

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

            $params = [
                'json' => [
                    'image' => $imageImageRepository->getName().'.img',
                    'repo_ip' => $imageImageRepository->getRepository()->getIp(),
                    'user' => $repository->getUser() ?? 'opengnsys',
                    'ssh_port' => $repository->getSshPort() ?? '22',
                ]
            ];

            $this->logger->info('Importing image', ['image' => $imageImageRepository->getName(), 'repository' => $repository->getIp(), 'ssh_port' => $repository->getSshPort(), 'user' => $repository->getUser()]);

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

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

            $inputData = [
                'imageName' => $image->getName(),
                'imageVersion' => $imageImageRepository->getVersion(),
                'imageCompleteName' => $imageImageRepository->getName(),
                'imageUuid' => $image->getUuid(),
                'imageImageRepositoryUuid' => $imageImageRepository->getUuid(),
                'repositoryUuid' => $repository->getUuid(),
            ];

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

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

        return new JsonResponse(data: [], status: Response::HTTP_OK);
    }
}