<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

use App\Dto\Input\MultipleClientsInput;
use App\Entity\Client;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

class RebootAction extends AbstractOgAgentController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(MultipleClientsInput $input): JsonResponse
    {
        foreach ($input->clients as $clientEntity) {
            /** @var Client $client */
            $client = $clientEntity->getEntity();


            if (!$client->getIp()) {
                throw new BadRequestHttpException('IP is required');
            }

            $data = [
                'nfn' => 'Reiniciar',
                'ids' => '0'
            ];

            $response = $this->createRequest(
                method: 'POST',
                url: 'https://'.$client->getIp().':8000/opengnsys/Reiniciar',
                params: [
                    'json' => $data,
                ],
                token: $client->getToken(),
            );

            if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
                if ($input->queue) {
                    $this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::PENDING, null, []);
                    continue;
                }
                
                continue;
            }

            $this->logger->info('Rebooting client', ['client' => $client->getId()]);

            $jobId = $response['job_id'];

            $client->setStatus(ClientStatus::INITIALIZING);
            $this->entityManager->persist($client);
            $this->entityManager->flush();

            $this->createService->__invoke($client, CommandTypes::REBOOT, TraceStatus::SUCCESS, $jobId, []);
        }

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