<?php

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

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 HandleRegistration
{
        public function __construct(
            public EntityManagerInterface $entityManager,
            public UserSaver $userSaver,
            public UserRepository $userRepository,
            public JWTTokenManagerInterface $tokenManager,
            public ValidatorInterface $validator

        ){}

        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.');
            }
            $userDto = new UserDto();
            $userDto->fillFromArray($requestArray);
            $userDto->validate();
            if (!empty($userDto->validationErrors))
            {
                return $this->generateErrorResponse($userDto->validationErrors);
            }
            $userDto->active = true;
            $newUser = new User();
            $newUser->setRoles(['ROLE_USER']);
            $newUser = $this->userSaver->save($newUser, $userDto);
            $this->entityManager->flush();
            $this->entityManager->clear();
            $userDto->id = $newUser->getId();
            $token = $this->tokenManager->create($newUser);
            return new JsonResponse(
                data: [
                    'success' => true,
                    'message' => 'Usuario creado.',
                    'token' => $token,
                    'user' => $userDto->toRegisterArray(),
                ],
                status: Response::HTTP_OK
            );
        }

        public function generateErrorResponse(array $validationErrors): JsonResponse
        {
            return new JsonResponse(
                data: [
                    'success' => false,
                    'errors' => $validationErrors
                ],
                status: Response::HTTP_BAD_REQUEST
            );
        }
}