<?php declare(strict_types=1);

namespace App\Controller\Page;

use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Security\AppAuthenticator;
use App\Service\TokenGenerator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;

class RegistrationController extends AbstractController
{
    #[Route('/register', name: 'app_register', methods: ['GET', 'POST'])]
    public function register(
        Request                     $request,
        UserPasswordHasherInterface $userPasswordHasher,
        UserAuthenticatorInterface  $userAuthenticator,
        AppAuthenticator            $authenticator,
        EntityManagerInterface      $entityManager,
        TokenGenerator              $tokenGenerator
    ): Response {
        // Create a new User entity
        $user = new User();

        // Create and process the registration form
        $form = $this->createForm(RegistrationFormType::class, $user)->handleRequest($request);

        // If the form is submitted and valid, create and authenticate the user
        if ($form->isSubmitted() && $form->isValid()) {
            // Hash the user's password
            $user->setPassword($userPasswordHasher->hashPassword($user, $form->get('plainPassword')->getData()));

            // Generate a unique registration token
            $user->setToken('ventry-' . $tokenGenerator->getRandomStringSha1(32));

            // Set time of registration
            $user->setCreatedAt(new \DateTimeImmutable());

            // Persist the user and their details
            $entityManager->persist($user);
            $entityManager->flush();

            // Authenticate the user and redirect to the home page
            $userAuthenticator->authenticateUser($user, $authenticator, $request);

            return $this->redirectToRoute('app_home');
        }

        // Render the registration form
        return $this->render('registration/register.html.twig', [
            'registrationForm' => $form->createView(),
        ]);
    }
}
