<?php

declare(strict_types=1);

namespace App\Controller;

use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Input\DeployGitImageInput;
use App\Entity\Command;
use App\Entity\Image;
use App\Model\ClientStatus;
use App\Entity\ImageImageRepository;
use App\Entity\OrganizationalUnit;
use App\Entity\Partition;
use App\Model\CommandTypes;
use App\Model\DeployMethodTypes;
use App\Model\TraceStatus;
use App\Service\Trace\CreateService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class DeployGitImageAction extends AbstractController
{
    public function __construct(
        protected readonly EntityManagerInterface $entityManager,
        protected readonly CreateService          $createService,
        protected readonly ValidatorInterface     $validator,
        public readonly \App\Controller\OgAgent\DeployGitImageAction $deployGitImageOgAgentAction,
    ) {
    }

    /**
     * @throws RedirectionExceptionInterface
     * @throws ClientExceptionInterface
     * @throws ServerExceptionInterface
     */
    public function __invoke(DeployGitImageInput $input): JsonResponse
    {
        $this->validator->validate($input);
        
        $clientJobs = $this->handleGitDeployment($input);

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

    private function handleGitDeployment(DeployGitImageInput $input): array
    {
        $clientJobs = [];

        foreach ($input->clients as $client) {
            $inputData = $this->createInputData($input, $client->getEntity());
            $jobId = $this->processDeployment($client->getEntity(), $input, $inputData, DeployMethodTypes::GIT);
            
            if ($jobId) {
                $clientJobs[(string) '/clients/' . $client->getEntity()->getUuid()] = $jobId;
            }
        }

        return $clientJobs;
    }

    private function processDeployment($client, DeployGitImageInput $input, array $inputData, string $deployType): ?string
    {
        $agentJobId = $this->deployGitImageOgAgentAction->__invoke($input, $client);
        
        if (!$agentJobId) {
            if ($input->queue) {
                $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::PENDING, null, $inputData);
            }
            return null;
        }

        $this->createService->__invoke($client, CommandTypes::DEPLOY_IMAGE, TraceStatus::IN_PROGRESS, $agentJobId, $inputData);
        
        return $agentJobId;
    }

    private function createInputData(DeployGitImageInput $input, $client): array
    {
        return [
            'method' => $input->method,
            'client' => $client->getUuid(),
            'hexsha' => $input->hexsha,
            'repositoryName' => $input->repositoryName,
            'branch' => $input->branch,
            'numDisk' => (string) $input->diskNumber,
            'numPartition' => (string) $input->partitionNumber,
            'type' => $input->type,
        ];
    }
} 