<?php

declare(strict_types=1);

namespace App\Controller\OgDhcp;

use App\Controller\OgBoot\PxeBootFile\PostAction;
use App\Service\Utils\GetIpAddressAndNetmaskFromCIDRService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\HttpException;
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]
abstract class AbstractOgDhcpController extends AbstractController
{
    public function __construct(
        #[Autowire(env: 'OG_DHCP_API_URL')]
        protected readonly string                                   $ogDhcpApiUrl,
        protected readonly EntityManagerInterface                   $entityManager,
        protected readonly GetIpAddressAndNetmaskFromCIDRService    $getIpAddressAndNetmaskFromCIDRService,
        protected readonly HttpClientInterface                      $httpClient,
    )
    {
    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function createRequest (string $method, string $url, array $params = []): JsonResponse|array
    {
        $params = array_merge($params, [
            'headers' => [
                'accept' => 'application/json',
                'Content-Type' => 'application/json'
            ],
        ]);

        try {
            $response = $this->httpClient->request($method, $url, $params);

            return json_decode($response->getContent(), true);
        } catch (ClientExceptionInterface | ServerExceptionInterface $e) {
            $response = $e->getResponse();
            $content = json_decode($response->getContent(false), true);
            throw new HttpException($response->getStatusCode(), $content['error'] ?? 'An error occurred');
        } catch (TransportExceptionInterface $e) {
            throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, $e->getMessage());
        }
    }
}
