<?php

namespace App\Controller\OgAgent;

use App\Dto\Input\SoftwareInventoryPartitionInput;
use App\Entity\Client;
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\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;

class SoftwareInventoryAction extends AbstractOgAgentController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(Client $client, SoftwareInventoryPartitionInput $input): JsonResponse
    {
        $data = [
            'nfn' => 'InventarioSoftware',
            'ids' => '0',
            'dsk' => (string) $input->partition->getEntity()->getDiskNumber(),
            'par' => (string) $input->partition->getEntity()->getPartitionNumber(),
        ];

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

        if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new BadRequestHttpException('Error performing software inventory: '.$response['error']);
        }

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

        $jobId = $response['job_id'];

        $inputData = [
            'partition' => $input->partition->getEntity()->getUuid(),
            'image' => $input->partition->getEntity()->getImage()?->getUuid(),
            'client' => $client->getIp(),
        ];

        $this->createService->__invoke($client, CommandTypes::SOFTWARE_INVENTORY, TraceStatus::IN_PROGRESS, $jobId, $inputData);

        return new JsonResponse(data: [], status: Response::HTTP_OK);
    }
}