<?php

namespace App\Tests\Security;

use App\Entity\Account;
use App\Security\KeycloakAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\OAuth2ClientInterface;
use League\OAuth2\Client\Provider\GenericResourceOwner;
use League\OAuth2\Client\Token\AccessToken;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\TestCase;
use Stevenmaguire\OAuth2\Client\Provider\KeycloakResourceOwner;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;

#[AllowMockObjectsWithoutExpectations]
class KeycloakAuthenticatorTest extends TestCase
{
    private $clientRegistry;
    private $entityManager;
    private $router;
    private $authenticator;

    protected function setUp(): void
    {
        $this->clientRegistry = $this->createMock(ClientRegistry::class);
        $this->entityManager = $this->createMock(EntityManagerInterface::class);
        $this->router = $this->createMock(RouterInterface::class);

        $this->authenticator = new KeycloakAuthenticator(
            $this->clientRegistry,
            $this->entityManager,
            $this->router
        );
    }

    public function testSupports()
    {
        $request = Request::create('/connect/keycloak/check');
        $request->attributes->set('_route', 'connect_keycloak_check');
        
        $this->assertTrue($this->authenticator->supports($request));
    }

    public function testAuthenticateExistingUser()
    {
        $request = Request::create('/connect/keycloak/check');
        
        $client = $this->createMock(OAuth2ClientInterface::class);
        $this->clientRegistry->method('getClient')->with('keycloak')->willReturn($client);
        
        $accessToken = new AccessToken(['access_token' => 'token']);
        $client->method('getAccessToken')->willReturn($accessToken);

        // Mock Keycloak User
        $keycloakUser = $this->createMock(KeycloakResourceOwner::class);
        $keycloakUser->method('getId')->willReturn('keycloak-id-123');
        $keycloakUser->method('getEmail')->willReturn('user@test.com');
        $client->method('fetchUserFromToken')->willReturn($keycloakUser);

        // Mock Repository
        $repository = $this->createMock(EntityRepository::class);
        $this->entityManager->method('getRepository')->with(Account::class)->willReturn($repository);
        
        // Existing user by Keycloak ID
        $existingUser = new Account();
        $repository->method('findOneBy')->willReturnMap([
            [['keycloakId' => 'keycloak-id-123'], null, $existingUser]
        ]);

        $passport = $this->authenticator->authenticate($request);
        
        $this->assertInstanceOf(Passport::class, $passport);
        $userBadge = $passport->getBadge(UserBadge::class);
        $userLoader = $userBadge->getUserLoader();
        $loadedUser = $userLoader();
        
        $this->assertSame($existingUser, $loadedUser);
    }
}
