<?php

namespace App\Controller\OgDhcp\Subnet;

use App\Controller\OgDhcp\AbstractOgDhcpController;
use App\Entity\Subnet;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
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 PostAction extends AbstractOgDhcpController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(Subnet $data): JsonResponse
    {
        $params = [
            'json' => [
                'subnetId' => rand(1, 1000),
                'mask' => $data->getNetmask(),
                'address' => $data->getIpAddress(),
                'nextServer' => $data->getNextServer(),
                'bootFileName' => $data->getBootFileName(),
                'router' => $data->getRouter(),
                'DNS' => $data->getDns()
            ]
        ];

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

        $data->setServerId($content['message']['id']);
        $data->setSynchronized(true);
        $this->entityManager->persist($data);
        $this->entityManager->flush();

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