<?php

namespace App\EventListener;

use App\Controller\OgBoot\PxeBootFile\DeleteAction;
use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Controller\OgDhcp\Subnet\PutHostAction;
use App\Entity\Client;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

#[AsEntityListener(event: Events::preUpdate, method: 'preUpdate', entity: Client::class)]
readonly class ClientMacListener
{
    public function __construct(
        private DeleteAction $deleteAction,
        private PutHostAction $putHostAction,
    )
    {

    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function preUpdate(Client $client, PreUpdateEventArgs $event): void
    {
        $em = $event->getObjectManager();
        $uow = $em->getUnitOfWork();
        $changeSet = $uow->getEntityChangeSet($client);

        if (!array_key_exists('mac', $changeSet)) {
            return;
        }

        $oldMac = isset($changeSet['mac'][0]) ? $changeSet['mac'][0] : null;

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

        if ($client->getSubnet()) { 
            $this->putHostAction->__invoke($oldMac, $client);
            $this->deleteAction->__invoke($oldMac);
        }
    }
}