<?php

namespace App\Security;

use App\Entity\Customer;
use App\Entity\OrderSession;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
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\SecurityRequestAttributes;

class FlowAuthenticator extends AbstractLoginFormAuthenticator
{
    public function __construct(
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly EntityManagerInterface $entityManager
    ) {}

    public function supports(Request $request): bool
    {
        return $request->attributes->get('_route') === 'reservation_flow'
            && $request->isMethod('POST');
    }

    public function authenticate(Request $request): Passport
    {
        $email = $request->getPayload()->getString('_username');
        $password = $request->getPayload()->getString('_password');
        $csrfToken = $request->getPayload()->getString('_csrf_token');

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

        return new Passport(
            new UserBadge($email, function (string $userIdentifier) {
                return $this->entityManager->getRepository(Customer::class)
                    ->findOneBy(['email' => $userIdentifier]);
            }),
            new PasswordCredentials($password),
            [
                new CsrfTokenBadge('authenticate_flow', $csrfToken),
                new RememberMeBadge(),
            ]
        );
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        $sessionId = $request->attributes->get('sessionId');

        // Associate customer with session
        /** @var Customer $customer */
        $customer = $token->getUser();
        $session = $this->entityManager->getRepository(OrderSession::class)
            ->findOneBy(['uuid' => $sessionId]);

        if ($session && $customer) {
            $session->setCustomer($customer);
            $this->entityManager->flush();
        }

        return new RedirectResponse($this->urlGenerator->generate('reservation_flow', ['sessionId' => $sessionId]));
    }

    protected function getLoginUrl(Request $request): string
    {
        $sessionId = $request->attributes->get('sessionId');
        return $this->urlGenerator->generate('reservation_flow', ['sessionId' => $sessionId]);
    }
}
