<?php

namespace DMD\LaLigaApi\Service\User\Handlers\delete;

use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class HandleDeleteUser
{
        public function __construct(
            public EntityManagerInterface $entityManager,
            public UserRepository $userRepository,
        ){}

        public function __invoke(Request $request): JsonResponse
        {
            $requestArray = $request->toArray();
            $existingUser = $this->userRepository->findOneBy(['email'=> $requestArray['email']]);
            if (!is_null($existingUser))
            {
                throw new HttpException(400,'Ya hay un usuario registrado con este correo.');
            }
            $this->entityManager->remove((object)$existingUser);
            $this->entityManager->flush();
            $this->entityManager->clear();
            return new JsonResponse(
                data: [
                    'success' => true,
                    'message' => 'Usuario eliminado.'
                ],
                status: Response::HTTP_OK
            );
        }
}