<?php

namespace App\Security;

use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class ApiUserProvider implements UserProviderInterface
{
    public function __construct(private UserRepository $userRepository)
    {
    }

    /**
     * Recharger l'utilisateur par pseudo (utilisé par le firewall)
     */
    public function loadUserByIdentifier(string $identifier): UserInterface
    {
        $user = $this->userRepository->findOneBy(['pseudo' => $identifier]);

        if (!$user) {
            throw new UserNotFoundException(sprintf('User "%s" not found', $identifier));
        }

        return $user;
    }

    /**
     * Vérifier si ce provider supporte la classe utilisateur
     */
    public function supportsClass(string $class): bool
    {
        return $class === 'App\Entity\User';
    }

    /**
     * Rafraîchir l'utilisateur (recharger depuis la BD)
     */
    public function refreshUser(UserInterface $user): UserInterface
    {
        if (!$this->supportsClass($user::class)) {
            throw new \InvalidArgumentException(sprintf('Instances of "%s" are not supported', $user::class));
        }

        $updatedUser = $this->userRepository->find($user->getId());

        if (!$updatedUser) {
            throw new UserNotFoundException(sprintf('User "%d" not found', $user->getId()));
        }

        return $updatedUser;
    }
}

