<?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\ViewInput;
use App\Dto\Output\ViewOutput;
use App\Repository\ViewRepository;
use Symfony\Component\Security\Core\Security;

readonly class ViewProcessor implements ProcessorInterface
{
    public function __construct(
        private ViewRepository                  $viewRepository,
        private ValidatorInterface              $validator,
        private Security                        $security
    )
    {
    }

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

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

        $view = $data->createOrUpdateEntity($entity);
        $view->setUser($this->security->getUser());
        $this->validator->validate($view);
        $this->viewRepository->save($view);

        return new ViewOutput($view);
    }

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

        return null;
    }
}
