<?php

namespace App\Security;

use App\Entity\ApiKey;
use App\Repository\ApiKeyRepository;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class ApiTokenHandler implements AccessTokenHandlerInterface
{
    public function __construct(private ApiKeyRepository $apiKeyRepository)
    {
    }

    public function getUserBadgeFrom(string $credentials): UserBadge
    {
        $apiKey = $this->apiKeyRepository->findValidByToken($credentials);

        if (!$apiKey) {
            throw new BadCredentialsException('Invalid API token');
        }

        // Mettre à jour le dernier accès
        $apiKey->setLastUsedAt(new \DateTime());
        $this->apiKeyRepository->getEntityManager()->flush();

        return new UserBadge($apiKey->getUser()->getPseudo());
    }
}

