<?php

namespace App\Controller\OgDhcp\Subnet;

use App\Controller\OgDhcp\AbstractOgDhcpController;
use App\Entity\Client;
use App\Entity\Subnet;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsController]
class DeleteHostAction extends AbstractOgDhcpController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(Subnet $data, string $clientUuid): JsonResponse
    {
        $client = $this->entityManager->getRepository(Client::class)->findOneBy(['uuid' => $clientUuid]);

        if (!$client) {
            throw new BadRequestHttpException('Client not found');
        }

        if (!$data->getId()) {
            throw new BadRequestHttpException('Data URL is required');
        }

        $params = [
            'json' => [
                'macAddress' => strtolower($client->getMac()),
            ]
        ];

        $content = $this->createRequest('DELETE', 'http://'.$this->ogDhcpApiUrl.'/ogdhcp/v1/subnets/'.$data->getServerId().'/hosts', $params);

        $data->removeClient($client);
        $this->entityManager->persist($data);
        $this->entityManager->flush();

        return new JsonResponse(data: $content, status: Response::HTTP_OK);
    }
}