<?php
namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
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;

class JwtAuthenticator extends AbstractAuthenticator
{
    public function __construct(
        private JWTTokenManagerInterface $jwtManager,
        private EntityManagerInterface    $em
    ) {}

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        /** @var User $user */
        $user = $token->getUser();

        return new JsonResponse([
            '@id' => '/api/users/' . $user->getId(),
            'dbId' => $user->getId(),
            'token' => $this->jwtManager->create($user)
        ]);
    }

    public function supports(Request $request): ?bool
    {
        return $request->getPathInfo() === '/api/auth' && $request->isMethod('POST');
    }

    public function authenticate(Request $request): Passport
    {
        $data = json_decode($request->getContent(), true);
        if (!$data) {
            throw new CustomUserMessageAuthenticationException('Ungültige JSON-Daten.');
        }

        $email    = $data['email'] ?? '';
        $password = $data['password'] ?? '';

        $userBadge = new UserBadge($email, function(string $userIdentifier) {
            $user = $this->em
                ->getRepository(User::class)
                ->findOneBy(['email' => $userIdentifier]);

            if (!$user) {
                // Standardnachricht für nicht gefundene E-Mail
                throw new CustomUserMessageAuthenticationException('Invalid email or password.');
            }

            if (!$user->isActive()) {
                // custom Message, erscheint im JSON-Response
                throw new CustomUserMessageAuthenticationException('Your account is currently deactivated.');
            }

            return $user;
        });

        return new Passport(
            $userBadge,
            new PasswordCredentials($password)
        );
    }


    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse([
            'message' => $exception->getMessage()
        ], Response::HTTP_UNAUTHORIZED);
    }
}