<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

use App\Dto\Input\KillJobInput;
use App\Entity\Trace;
use App\Model\ClientStatus;
use App\Model\CommandTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
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 KillJobAction extends AbstractOgAgentController
{
    /**
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     */
    public function __invoke(Trace $trace, KillJobInput $input): JsonResponse
    {
        $client = $trace->getClient();

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

        $data = [
            'job_id' => $input->jobId
        ];

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

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

        $this->logger->info('Killing job', ['client' => $client->getId(), 'job_id' => $input->jobId]);

        $trace->setStatus(TraceStatus::CANCELLED);
        $this->entityManager->persist($trace);
        $this->entityManager->flush();

        $inputData = [
            'job_id' => $input->jobId,
            'client' => $client->getId(),
            'trace' => $trace->getUuid(),
            'command' => $trace->getCommand(),
        ];

        $this->createService->__invoke($client, CommandTypes::KILL_JOB, TraceStatus::CANCELLED, $input->jobId, $inputData);

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