<?php

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

use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\UserSaver;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
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 HandleUpdateUser
{
        public function __construct(
            public EntityManagerInterface $entityManager,
            public Security $security,
            public UserSaver $userSaver,
            public UserRepository $userRepository,
            public JWTTokenManagerInterface $tokenManager,
            public ValidatorInterface $validator

        ){}

        public function __invoke(Request $request): JsonResponse
        {
            $requestArray = $request->toArray();
            $requestUserEmail = $this->security->getUser()?->getUserIdentifier();
            $requestUserObj = $this->userRepository->findOneBy([
                'email' => $requestUserEmail
            ]);
            if (is_null($requestUserObj))
            {
                throw new HttpException(500, 'Usuario no encontrado.');
            }
            $userDto = new UserDto();
            $userDto->fillFromObject($requestUserObj);
            $userDto->fillFromArray($requestArray);
            $userDto->validate();
            if (!empty($userDto->validationErrors))
            {
                $this->generateErrorResponse($userDto->validationErrors);
            }
            $editedUserObj = $this->userSaver->save($requestUserObj, $userDto);
            $this->entityManager->flush();
            $this->entityManager->clear();
            $userDto->id = $editedUserObj->getId();
            return new JsonResponse(
                data: [
                    'success' => true,
                    'message' => 'Usuario editado.',
                    'user' => $userDto->toArray(),
                ],
                status: Response::HTTP_OK
            );
        }

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