<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

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

        if (!$input->hexsha) {
            throw new BadRequestHttpException('Either hexsha or tag is required for Git image deployment');
        }

        if (!$input->repositoryName) {
            throw new BadRequestHttpException('Repository name is required for Git image deployment');
        }

        if (!$input->branch) {
            throw new BadRequestHttpException('Branch is required for Git image deployment');
        }

        $repository = $client->getRepository();

        $data = [
            'disk' => (string) $input->diskNumber,
            'partition' => (string) $input->partitionNumber,
            'idi' => $input->repositoryName,
            'image_name' => $input->repositoryName,
            'repository' => $repository->getIp(),
            'nfn' => 'RestaurarImagenGit',  
            'ids' => '0',
            'commit' => $input->hexsha,
            'branch' => $input->branch
        ];

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

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

        $this->logger->info('Deploying Git image', [ 
            'repository' => $input->repositoryName,
            'branch' => $input->branch,
            'ref' => $input->hexsha,
            'client' => $client->getIp()
        ]);

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

        $jobId = $response['job_id'];

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

        return $jobId;
    }
} 