<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\RegistrationFormType;
use App\Form\ResetPasswordRequestFormType;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;

class SecurityController extends AbstractController
{
    use ResetPasswordControllerTrait;

    public function __construct(private readonly ResetPasswordHelperInterface $resetPasswordHelper,
                                private readonly EntityManagerInterface       $entityManager,
                                private readonly VerifyEmailHelperInterface   $verifyEmailHelper,
                                private readonly MailerInterface              $mailer,
    )
    {
        // empty body
    }

    #[Route(path: '/security/login', name: 'security_login')]
    public function index(AuthenticationUtils $authenticationUtils): Response
    {
        // get the login error if there is one
        if ($error = $authenticationUtils->getLastAuthenticationError()) {
            $this->addFlash(type: 'error', message: $error->getMessageKey());
        }

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render(view: '@default/security/login.html.twig', parameters: [
            'last_username' => $lastUsername,
            'error' => '',
        ]);
    }

    /**
     * @throws Exception
     */
    #[Route(path: '/security/logout', name: 'security_logout')]
    public function logout(): never
    {
        throw new Exception(message: 'Logout should never be reached.');
    }

    #[Route(path: '/security/register', name: 'security_register')]
    public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(type: RegistrationFormType::class);
        $form->handleRequest(request: $request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();
            // hash the plain password
            $user->setPassword(
                password: $userPasswordHasher->hashPassword(
                    user: $user,
                    plainPassword: $form->get(name: 'password')->getData()
                )
            );

            if ($form->get(name: 'agreeTerms')->getData()) {
                $user->agreeTerms();
            } // no else, we already confirmed in the form itself
            $entityManager->persist(entity: $user);
            $entityManager->flush();
            $this->generateSignedUrlAndEmailToTheUser($user);

            return $this->render(view: '@default/security/registration_finished.html.twig');
        }

        return $this->render(view: '@default/security/register.html.twig', parameters: [
            'registrationForm' => $form->createView(),
        ]);
    }

    #[Route(path: '/security/verify/email', name: 'security_verify_email')]
    public function verifyUserEmail(Request $request, TranslatorInterface $translator, UserRepository $userRepository): Response
    {
        $id = $request->get(key: 'id');

        if ($id === null) {
            return $this->redirectToRoute(route: 'app_register');
        }

        $user = $userRepository->find($id);

        if ($user === null) {
            return $this->redirectToRoute(route: 'app_register');
        }

        // validate email confirmation link, sets User::isVerified=true and persists
        try {
            $this->handleEmailConfirmation(request: $request, user: $user);
        } catch (VerifyEmailExceptionInterface $exception) {
            $this->addFlash(type: 'error', message: $translator->trans(id: $exception->getReason(), parameters: [], domain: 'VerifyEmailBundle'));

            return $this->redirectToRoute(route: 'app_main');
        }

        $this->addFlash(type: 'success', message: 'Your email address has been verified.');

        return $this->redirectToRoute(route: 'app_main');
    }

    /**
     * Display & process form to request a password reset.
     */
    #[Route(path: '/security/forgot/password', name: 'security_forgot_password')]
    public function request(Request $request, MailerInterface $mailer): Response
    {
        $form = $this->createForm(type: ResetPasswordRequestFormType::class);
        $form->handleRequest(request: $request);

        if ($form->isSubmitted() && $form->isValid()) {
            return $this->processSendingPasswordResetEmail(
                formData: $form->get(name: 'account')->getData(),
                mailer: $mailer
            );
        }

        return $this->render(view: '@default/security/forgot_password.html.twig', parameters: [
            'requestForm' => $form->createView(),
        ]);
    }

    /**
     * Confirmation page after a user has requested a password reset.
     */
    #[Route(path: '/security/recovery/mail/sent', name: 'security_recovery_mail_sent')]
    public function checkEmail(): Response
    {
        // Generate a fake token if the user does not exist or someone hit this page directly.
        // This prevents exposing whether a user was found with the given email address or username or not
        if (null === ($resetToken = $this->getTokenObjectFromSession())) {
            $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
        }

        return $this->render(view: '@default/security/recovery_mail_sent.html.twig', parameters: [
            'resetToken' => $resetToken,
        ]);
    }

    /**
     * Validates and process the reset URL that the user clicked in their email.
     */
    #[Route(path: '/security/recovery/reset/{token}', name: 'security_recovery_reset')]
    public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
    {
        if ($token) {
            // We store the token in session and remove it from the URL, to avoid the URL being
            // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
            $this->storeTokenInSession(token: $token);

            return $this->redirectToRoute(route: 'security_recovery_reset');
        }

        $token = $this->getTokenFromSession();
        if (null === $token) {
            throw $this->createNotFoundException(message: 'No reset password token found in the URL or in the session.');
        }

        try {
            $user = $this->resetPasswordHelper->validateTokenAndFetchUser(fullToken: $token);
        } catch (ResetPasswordExceptionInterface $e) {
            $this->addFlash(type: 'reset_password_error', message: sprintf(
                '%s - %s',
                $translator->trans(id: ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, parameters: [], domain: 'ResetPasswordBundle'),
                $translator->trans(id: $e->getReason(), parameters: [], domain: 'ResetPasswordBundle')
            ));

            return $this->redirectToRoute(route: 'app_forgot_password_request');
        }

        // The token is valid; allow the user to change their password.
        $form = $this->createForm(type: ChangePasswordFormType::class);
        $form->handleRequest(request: $request);

        if ($form->isSubmitted() && $form->isValid()) {
            // A password reset token should be used only once, remove it.
            $this->resetPasswordHelper->removeResetRequest(fullToken: $token);

            // Encode(hash) the plain password, and set it.
            $encodedPassword = $passwordHasher->hashPassword(
                user: $user,
                plainPassword: $form->get(name: 'plainPassword')->getData()
            );

            $user->setPassword($encodedPassword);
            $this->entityManager->flush();

            // The session is cleaned up after the password has been changed.
            $this->cleanSessionAfterReset();

            $this->addFlash(type: 'success', message: 'Your password has been changed.');

            return $this->redirectToRoute(route: 'app_main');
        }

        return $this->render(view: '@default/security/reset_password.html.twig', parameters: [
            'resetForm' => $form->createView(),
        ]);
    }

    private function processSendingPasswordResetEmail(string $formData, MailerInterface $mailer): RedirectResponse
    {
        $user = $this->entityManager->getRepository(entityName: User::class)->findOneBy(criteria: [
            'email' => $formData,
        ]);

        if (!$user) {
            $user = $this->entityManager->getRepository(entityName: User::class)->findOneBy(criteria: [
                'username' => $formData,
            ]);
        }

        // Do not reveal whether a user account was found or not.
//        if (!$user) {
//            return $this->redirectToRoute(route: 'app_check_email');
//        }

        try {
            $resetToken = $this->resetPasswordHelper->generateResetToken(user: $user);
        } catch (ResetPasswordExceptionInterface $e) {
            $this->addFlash(type: 'reset_password_error', message: sprintf(
                '%s - %s',
                ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
                $e->getReason()
            ));

            return $this->redirectToRoute(route: 'security_forgot_password');
        }

        $email = (new TemplatedEmail())
            ->from(new Address(address: 'tracer@24unix.net', name: '24unix.net'))
            ->to($user->getEmail())
            ->subject(subject: 'Your password reset request')
            ->htmlTemplate(template: '@default/security/mail/recovery.html.twig')
            ->context(context: [
                'resetToken' => $resetToken,
            ]);

        try {
            $mailer->send(message: $email);
        } catch (TransportExceptionInterface $e) {
            $this->addFlash(type: 'error', message: $e->getMessage());
        }

        // Store the token object in session for retrieval in check-email route.
        $this->setTokenObjectInSession(token: $resetToken);

        return $this->redirectToRoute(route: 'security_recovery_mail_sent');
    }


    public function sendEmailConfirmation(string $verifyEmailRouteName, User /* UserInterface */ $user, TemplatedEmail $email): void
    {
        $signatureComponents = $this->verifyEmailHelper->generateSignature(
            routeName: $verifyEmailRouteName,
            userId: $user->getId(),
            userEmail: $user->getEmail(),
            extraParams: ['id' => $user->getId()]
        );

        $context = $email->getContext();
        $context['signedUrl'] = $signatureComponents->getSignedUrl();
        $context['expiresAtMessageKey'] = $signatureComponents->getExpirationMessageKey();
        $context['expiresAtMessageData'] = $signatureComponents->getExpirationMessageData();

        $email->context(context: $context);

        try {
            $this->mailer->send(message: $email);
        } catch (TransportExceptionInterface $e) {
            die($e->getMessage());
        }
    }

    /**
     * @throws VerifyEmailExceptionInterface
     */
    public function handleEmailConfirmation(Request $request, User /*UserInterface*/ $user): void
    {
            $this->verifyEmailHelper->validateEmailConfirmation(signedUrl: $request->getUri(), userId: $user->getId(), userEmail: $user->getEmail());
            $user->setIsVerified(isVerified: true);
            $this->entityManager->persist(entity: $user);
            $this->entityManager->flush();
    }

    /**
     * @param mixed $user
     * @return void
     */
    public function generateSignedUrlAndEmailToTheUser(mixed $user): void
    {
        $this->sendEmailConfirmation(verifyEmailRouteName: 'security_verify_email', user: $user,
            email: (new TemplatedEmail())
                ->from(new Address(address: 'info@24unix.net', name: '24unix.net'))
                ->to($user->getEmail())
                ->subject(subject: 'Please Confirm your Email')
                ->htmlTemplate(template: '@default/security/mail/registration.html.twig')
                ->context(context: [
                    'username' => $user->getUsername()
                ])
        );
    }


    #[Route('/security/resend/verify_email', name: 'security_resend_verify_email')]
    public function resendVerifyEmail(Request $request, UserRepository $userRepository)
    {

        if ($request->isMethod('POST')) {

            $email = $request->getSession()->get('non_verified_email');
            $user = $userRepository->findOneBy(['email' => $email]);
            if (!$user) {
                throw $this->createNotFoundException('user not found for email');
            }

            $this->generateSignedUrlAndEmailToTheUser(user: $user);
            $this->addFlash('success', 'eMail has been sent.');

            return $this->redirectToRoute('app_main');
        }
        return $this->render('@default/security/resend_activation.html.twig');
    }
}
