<?php

namespace App\Security;

use App\Repository\UserRepository;
use Exception;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
    use TargetPathTrait;

    /**
     * @var UserRepository
     */
    private $userRepository;

    public const LOGIN_ROUTE = 'app_login';

    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    /**
     * @var UserPasswordHasherInterface
     */
    private $passwordEncoder;


    // https://symfony.com/doc/current/security/authenticator_manager.html

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param UserRepository $userRepository
     */
    public function __construct(
        UrlGeneratorInterface $urlGenerator,
        UserRepository $userRepository,
        UserPasswordHasherInterface $passwordEncoder)
    {
        $this->urlGenerator = $urlGenerator;
        $this->userRepository=$userRepository;
        $this->passwordEncoder=$passwordEncoder;
    }

    /**
     * @param Request $request
     * @return PassportInterface
     */
    public function authenticate(Request $request): PassportInterface
    {
        $email = $request->request->get('email', '');

        $request->getSession()->set(Security::LAST_USERNAME, $email);

        return new Passport(
            new UserBadge($email, function ($userIdentifier) {
                $user=$this->userRepository->findOneBy(['email' => $userIdentifier]);
                if ($user == null)
                    throw new CustomUserMessageAuthenticationException('Invalid credentials');
                return $user ;
            }),
            new PasswordCredentials($request->request->get('password', '')),
            [
                new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
            ]
        );
    }

    /**
     * @param Request $request
     * @param TokenInterface $token
     * @param string $firewallName
     * @return Response|null
     * @throws Exception
     */
    public function onAuthenticationSuccess(Request        $request,
                                            TokenInterface $token,
                                            string         $firewallName): ?Response
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
            return new RedirectResponse($targetPath);
        }
        $email = $request->request->get('email', '');
        $user=$this->userRepository->findOneBy(['email' => $email]);
        if (!$user)
            return new RedirectResponse($this->urlGenerator->generate('/login'));

        $organisation = $user->getOrganisation();
        if (! $organisation)
            return new RedirectResponse($this->urlGenerator->generate('app.home'));
        else
            return new RedirectResponse($this->urlGenerator->generate('app.'.$organisation.'.home'));

    }

    /**
     * @param Request $request
     * @return string
     */
    protected function getLoginUrl(Request $request): string
    {
        return $this->urlGenerator->generate(self::LOGIN_ROUTE);
    }
}
