<?php

namespace App\State\Processor;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Validator\ValidatorInterface;
use App\Dto\Input\GitRepositoryInput;
use App\Dto\Output\GitRepositoryOutput;
use App\Service\ExternalGitRepositoryService;
use App\Repository\ImageRepositoryRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\KernelInterface;

readonly class GitRepositoryProcessor implements ProcessorInterface
{
    public function __construct(
        private ExternalGitRepositoryService $externalService,
        private ImageRepositoryRepository $imageRepositoryRepository,
        private ValidatorInterface $validator,
        private RequestStack $requestStack,
        private KernelInterface $kernel
    )
    {
    }

    /**
     * @throws \Exception
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
    {
        switch ($operation){
            case $operation instanceof Post:
            case $operation instanceof Put:
            case $operation instanceof Patch:
                return $this->processCreateOrUpdate($data, $operation, $uriVariables, $context);
            case $operation instanceof Delete:
                return $this->processDelete($data, $operation, $uriVariables, $context);
        }
    }

    /**
     * @throws \Exception
     */
    private function processCreateOrUpdate($data, Operation $operation, array $uriVariables = [], array $context = []): GitRepositoryOutput
    {
        if (!($data instanceof GitRepositoryInput)) {
            throw new \Exception(sprintf('data is not instance of %s', GitRepositoryInput::class));
        }

        // Obtener el repositoryId del input data
        $repositoryId = $data->repository;
        
        if (!$repositoryId) {
            throw new \InvalidArgumentException('El campo "repository" es requerido');
        }

        $imageRepository = $this->imageRepositoryRepository->find($repositoryId);
        if (!$imageRepository) {
            throw new \Exception('ImageRepository no encontrado');
        }

        $gitRepository = $data->createOrUpdateEntity();
        $gitRepository->setRepository($imageRepository);
        
        $this->validator->validate($gitRepository);

        if ($this->kernel->getEnvironment() !== 'test') {
            try {
                if ($operation instanceof Post) {
                    $this->externalService->createRepository($gitRepository);
                } else {
                    $this->externalService->updateRepository($gitRepository);
                }
            } catch (\Exception $e) {
                throw new \Exception('Error en operación con API externa: ' . $e->getMessage());
            }
        }

        return new GitRepositoryOutput($gitRepository);
    }

    private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        // Obtener el ImageRepository desde los parámetros
        $request = $this->requestStack->getCurrentRequest();
        $repositoryId = $request->query->get('repository');
        $name = $uriVariables['name'];
        
        if (!$repositoryId || !$name) {
            throw new \InvalidArgumentException('Los parámetros "repository" y "name" son requeridos');
        }

        $imageRepository = $this->imageRepositoryRepository->find($repositoryId);
        if (!$imageRepository) {
            throw new \Exception('ImageRepository no encontrado');
        }

        if ($this->kernel->getEnvironment() !== 'test') {
            try {
                $this->externalService->deleteRepository($name, $imageRepository);
            } catch (\Exception $e) {
                throw new \Exception('Error eliminando repositorio en API externa: ' . $e->getMessage());
            }
        }

        return null;
    }
} 