<?php

namespace App\Controller\OgRepository\Image;

use App\Controller\OgRepository\AbstractOgRepositoryController;
use App\Dto\Input\ExportImportImageRepositoryInput;
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 Doctrine\Common\Collections\ArrayCollection;
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 TransferGlobalAction extends AbstractOgRepositoryController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(ImageImageRepository $imageImageRepository): JsonResponse
    {
        $repositories = $this->entityManager->getRepository(ImageRepository::class)->findAll();

        foreach ($repositories as $repository) {

            $hasImage = $this->entityManager->getRepository(ImageImageRepository::class)
                ->findOneBy(['image' => $imageImageRepository->getImage(), 'repository' => $repository]);

            if ($hasImage) {
                continue;
            }

            $image = $imageImageRepository->getImage();

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

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

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

            if (!isset($content['job_id'])) {
                throw new BadRequestHttpException('Job ID not found');
            }

            $inputData = [
                'imageName' => $image->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);

            $image->setIsGlobal(true);
            $this->entityManager->persist($image);

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

            $this->entityManager->flush();
        }

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