<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Controller\OgDhcp\Subnet\PutHostAction;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
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 ClientSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private PostAction $postAction,
        private PutHostAction $putHostAction,
    )
    {

    }

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

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

        if (!$clientOutput instanceof ClientOutput || (Request::METHOD_POST !== $method && Request::METHOD_PUT !== $method && Request::METHOD_PATCH !== $method)) {
            return;
        }

        /** @var Client $client */
        $client = $clientOutput->getEntity();

        $template = $client->getTemplate() ?
            $client->getTemplate() :
            $client->getOrganizationalUnit()?->getNetworkSettings()?->getPxeTemplate();

        if ($template === null) {
            $template = $this->entityManager->getRepository(PxeTemplate::class)->findOneBy(['isDefault' => true]);

            if ($template === null) {
                return;
            }
        }

        $this->postAction->__invoke($client, $template);

        if (!$client->getSubnet()) {
            return;
        }
        $this->putHostAction->__invoke($client->getMac(), $client);
    }
}