<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

use App\Dto\Input\UpdateGitImageInput;
use App\Entity\Client;
use App\Model\ClientStatus;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
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 UpdateGitImageAction extends AbstractOgAgentController
{
    /**
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws TransportExceptionInterface
     * @throws ServerExceptionInterface
     */
    public function __invoke(UpdateGitImageInput $input, Client $client)
    {
        if (!$client->getIp()) {
            throw new BadRequestHttpException('IP is required');
        }

        if (!$input->gitRepository) {
            throw new BadRequestHttpException('Git repository name is required for Git image update');
        }

        $partition = $input->partition->getEntity();
        $repository = $client->getRepository();

        $data = [
            'disk' => (string) $partition->getDiskNumber(),
            'partition' => (string) $partition->getPartitionNumber(),
            'idi' => $input->gitRepository,
            'image_name' => $input->gitRepository,
            'repository' => $repository->getIp(),
            'message' => 'updating git image',
            'nfn' => 'ModificarImagenGit',
            'ids' => '0',
            'branch' => $input->destinationBranch,
            'options' => $input->options ? 'force_push' : null,
        ];

        $url = 'https://'.$client->getIp().':8000/opengnsys/ModificarImagenGit';

        $response = $this->createRequest(
            method: 'POST',
            url: $url,
            params: [
                'json' => $data,
            ],
            token: $client->getToken(),
        );

        $this->logger->info('Updating Git image', [ 
            'repository' => $input->gitRepository,
            'client' => $client->getIp(),
            'disk' => $partition->getDiskNumber(),
            'partition' => $partition->getPartitionNumber()
        ]);

        if (isset($response['error']) && $response['code'] === Response::HTTP_INTERNAL_SERVER_ERROR) {
            throw new BadRequestHttpException('Error updating Git image');
        }

        $jobId = $response['job_id'];

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

        return $jobId;
    }
} 