<?php

namespace DMD\LaLigaApi\Controller;

use DMD\LaLigaApi\Repository\UserRepository;
use DMD\LaLigaApi\Service\User\Handlers\delete\HandleDeleteUser;
use DMD\LaLigaApi\Service\User\Handlers\getRelationships\HandleGetUserRelationships;
use DMD\LaLigaApi\Service\User\Handlers\update\HandleUpdateUser;
use DMD\LaLigaApi\Service\User\Handlers\register\HandleRegistration;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;

class UserController extends AbstractController
{
    #[Route('/api/register', name: 'app_user_register', methods: ['POST'])]
    public function createUser(Request $request, HandleRegistration $handleRegistration): JsonResponse
    {
        return $handleRegistration($request);
    }
    #[Route('/api/user/', name: 'app_user_delete', methods: ['DELETE'])]
    public function deleteUser(Request $request, HandleDeleteUser $handleDeleteUser): JsonResponse
    {
        return $handleDeleteUser($request);
    }

    #[Route('/api/user/edit', name: 'app_update_user', methods: ['PUT'])]
    public function updateUser(Request $request, HandleUpdateUser $handleUpdateUser): JsonResponse
    {
        return $handleUpdateUser($request);
    }

    #[Route('/api/user/password', name: 'app_user_change_password', methods: ['PUT'])]
    public function changePassword(
        Request $request,
        UserRepository $userRepository,
        UserPasswordHasherInterface $passwordHasher,
        EntityManagerInterface $entityManager
    ): JsonResponse
    {
        $user = $userRepository->findOneBy([
            'email' => ($request->toArray())['username']
        ]);
        if (is_null($user))
        {
            throw new HttpException(
                Response::HTTP_NOT_FOUND,
                'User not found.'
            );
        }
        $hashedPassword = $passwordHasher->hashPassword($user, ($request->toArray())['newPassword']);
        $user->setPassword($hashedPassword);
        $entityManager->persist($user);
        $entityManager->flush($user);
        $entityManager->clear();
        return new JsonResponse([
            'success' => true
        ]);
    }
}