<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Controller\OgRepository\Image\TransferGlobalAction;
use App\Dto\Output\ImageRepositoryOutput;
use App\Dto\Output\OrganizationalUnitOutput;
use App\Entity\Image;
use App\Entity\ImageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

final readonly class ImageRepositorySubscriber implements EventSubscriberInterface
{
    public function __construct(
        private EntityManagerInterface        $entityManager,
        private readonly TransferGlobalAction $transferIsGlobalAction,
    )
    {

    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['transferImages', EventPriorities::POST_WRITE],
        ];
    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function transferImages(ViewEvent $event): void
    {
        $imageRepositoryOutput = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$imageRepositoryOutput instanceof ImageRepositoryOutput ||
            $method != Request::METHOD_POST) {
            return;
        }

        $imagesToImport = $this->entityManager->getRepository(Image::class)->findBy(['isGlobal' => true]);

        foreach($imagesToImport as $imageToImport) {
            //$this->transferIsGlobalAction->__invoke($imageRepositoryOutput->getEntity());
        }
    }
}