<?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\UserInput;
use App\Dto\Output\UserOutput;
use App\Repository\UserRepository;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly UserRepository     $userRepository,
        private readonly ValidatorInterface $validator,
        private readonly UserPasswordHasherInterface $userPasswordHasher
    )
    {
    }

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

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

        $user = $data->createOrUpdateEntity($user);

        if ($data->password !== null){
            $user->setPassword($this->userPasswordHasher->hashPassword($user, $data->password));
        }

        $this->validator->validate($user);
        $this->userRepository->save($user);

        return new UserOutput($user);
    }

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

        return null;
    }
}
