<?php

namespace App\Service\OgBoot;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
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;
use Symfony\Component\HttpClient\HttpClient;


readonly class StatusService
{
    public function __construct(
        #[Autowire(env: 'OG_BOOT_IP')]
        protected string                                    $ogBootIp,
        #[Autowire(env: 'OG_BOOT_PXE_PORT')]
        protected string                                    $ogBootPxePort,
        #[Autowire(env: 'OG_BOOT_API_PORT')]
        protected string                                    $ogBootApiPort,
    )
    {
    }

    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke()
    {
        $httpClient = HttpClient::create([
            'verify_peer' => false,
            'verify_host' => false,
        ]);

        try {
            $response = $httpClient->request('GET', 'http://' . $this->ogBootIp . ':' . $this->ogBootApiPort . '/ogboot/v1/status', [
                'headers' => ['accept' => 'application/json'],
            ]);

            return json_decode($response->getContent(), true);

        } catch (ClientExceptionInterface | ServerExceptionInterface $e) {
            return [
                'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
                'error' => 'Client/Server error',
                'details' => $e->getMessage(),
            ];
        } catch (TransportExceptionInterface $e) {
            return [
                'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
                'error' => 'Transport error',
                'details' => $e->getMessage(),
            ];
        }
    }

}