<?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\ImageRepositoryInput;
use App\Dto\Output\ImageRepositoryOutput;
use App\Repository\ImageRepositoryRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Client;

readonly class ImageRepositoryProcessor implements ProcessorInterface
{
    public function __construct(
        private ImageRepositoryRepository     $imageRepository,
        private ValidatorInterface  $validator,
        private EntityManagerInterface $entityManager

        )
    {
    }

    /**
     * @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 = []): ImageRepositoryOutput
    {
        if (!($data instanceof ImageRepositoryInput)) {
            throw new \Exception(sprintf('data is not instance of %s', ImageRepositoryInput::class));
        }

        $entity = null;
        if (isset($uriVariables['uuid'])) {
            $entity = $this->imageRepository->findOneByUuid($uriVariables['uuid']);
        }

        $repository = $data->createOrUpdateEntity($entity);
        $this->validator->validate($repository);
        $this->imageRepository->save($repository);

        return new ImageRepositoryOutput($repository);
    }

    private function processDelete($data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        $repository = $this->imageRepository->findOneByUuid($uriVariables['uuid']);

        $clients = $this->entityManager->getRepository(Client::class)->findBy(['repository' => $repository]);

        foreach ($clients as $client) {
            $client->setRepository($client->getOrganizationalUnit()?->getNetworkSettings()?->getRepository());
            $this->entityManager->persist($client);
            $this->entityManager->flush();
        }
        
        $this->imageRepository->delete($repository);

        return null;
    }
}
