<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Controller\OgBoot\PxeTemplate\PostAction;
use App\Dto\Output\OrganizationalUnitOutput;
use App\Dto\Output\PxeTemplateOutput;
use App\Entity\Client;
use App\Entity\NetworkSettings;
use App\Entity\OrganizationalUnit;
use App\Entity\PxeTemplate;
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 PxeTemplateSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly PostAction $postTemplateAction,
        private readonly \App\Controller\OgBoot\PxeBootFile\PostAction $postAction,
        private readonly EntityManagerInterface $entityManager,
    )
    {

    }

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

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

        if (!$pxeTemplateOutput instanceof PxeTemplateOutput ||
            !in_array($method, [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH])) {
            return;
        }

        /** @var PxeTemplate $templateEntity */
        $templateEntity = $pxeTemplateOutput->getEntity();

        try {
            $this->postTemplateAction->__invoke($templateEntity);
        } catch (\Exception $e) {
            return ;
        }

        $clients = $this->entityManager->getRepository(Client::class)->findBy(['template' => $templateEntity]);

        foreach ($clients as $client) {
            $this->postAction->__invoke($client, $templateEntity);
        }
    }
}