<?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\ImageImageRepositoryInput;
use App\Dto\Output\ImageImageRepositoryOutput;
use App\Repository\ImageImageRepositoryRepository;
use Doctrine\ORM\EntityManagerInterface;

readonly class ImageImageRepositoryProcessor implements ProcessorInterface
{
    public function __construct(
        private ImageImageRepositoryRepository      $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 = []): ImageImageRepositoryOutput
    {
        if (!($data instanceof ImageImageRepositoryInput)) {
            throw new \Exception(sprintf('data is not instance of %s', ImageImageRepositoryInput::class));
        }

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

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

        return new ImageImageRepositoryOutput($image);
    }

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

        $repository = $imageImageRepository->getRepository();
        $image = $imageImageRepository->getImage();

        $imageImageCollection = $image->getImageImageRepositories();

        if ($imageImageCollection->isEmpty()) {
            $this->entityManager->remove($image);
            $this->entityManager->flush();
        }

        return null;
    }
}
