<?php

declare(strict_types=1);

namespace App\Controller\OgAgent;

use App\Dto\Input\DeployGitImageInput;
use App\Entity\Client;
use App\Entity\Image;
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 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 && !$input->tag) {
            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 = [
            'dsk' => (string) $input->diskNumber,
            'par' => (string) $input->partitionNumber,
            'ifs' => "1",
            'idi' => 1,
            'nci' => $input->repositoryName,
            'ipr' => $repository->getIp(),
            'nfn' => 'RestaurarImagenGit',
            'ptc' => 'git', 
            'ids' => '0',
            'ref' => $input->hexsha ?? $input->tag
        ];

        $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 ?? $input->tag,
            '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;
    }
} 