<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

/**
 * Authenticateur pour les tokens API (Bearer tokens)
 * Utilisé uniquement si un header Authorization est présent
 * Laisse la session tranquille si pas de token
 */
class ApiBearerTokenAuthenticator extends AbstractAuthenticator
{
    public function __construct(private ApiTokenHandler $tokenHandler)
    {
    }

    public function supports(Request $request): ?bool
    {
        // Seulement si c'est un Bearer token
        return $request->headers->has('Authorization') &&
               str_starts_with($request->headers->get('Authorization', ''), 'Bearer ');
    }

    public function authenticate(Request $request): Passport
    {
        $authHeader = $request->headers->get('Authorization');
        $token = substr($authHeader, 7); // Enlever "Bearer "

        // Valider le token
        $userBadge = $this->tokenHandler->getUserBadgeFrom($token);
        return new SelfValidatingPassport($userBadge);
    }


    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?JsonResponse
    {
        // Laisser la requête continuer
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse
    {
        return new JsonResponse(
            [
                'error' => 'Unauthorized',
                'message' => 'Invalid or expired API token',
            ],
            401
        );
    }
}

