<?php

namespace NoahVet\Reef\HWI\OAuth;

use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use NoahVet\Reef\HWI\OAuth\Response\ReefUserResponse;
use NoahVet\Reef\Jane\Model\UserinfoGetResponse200;
use NoahVet\Reef\Security\User\ReefOAuthUser;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Polyfill\Intl\Icu\Exception\NotImplementedException;

/**
 * @implements UserProviderInterface<UserInterface>
 */
class ReefUserProvider implements OAuthAwareUserProviderInterface, UserProviderInterface
{
    #[\Override]
    public function loadUserByOAuthUserResponse(UserResponseInterface $response): UserInterface
    {
        \assert($response instanceof ReefUserResponse);

        $userInfo = new UserinfoGetResponse200();
        $userInfo->setIdentifier($response->getUserIdentifier());
        $userInfo->setEmail($response->getEmail());
        $userInfo->setGivenName($response->getFirstName());
        $userInfo->setFamilyName($response->getLastName());
        $userInfo->setNickname($response->getNickname());
        $userInfo->setDisplayName($response->getRealName());
        $userInfo->setPreferredUsername($response->getEmail() ?? $response->getUserIdentifier());
        $userInfo->setGroups(\array_values($response->getGroups() ?? []));

        return ReefOAuthUser::createFromUserinfo($userInfo);
    }

    #[\Override]
    public function refreshUser(UserInterface $user): UserInterface
    {
        return $user;
    }

    #[\Override]
    public function supportsClass(string $class): bool
    {
        return ReefOAuthUser::class === $class;
    }

    public function loadUserByUsername(string $username): UserInterface
    {
        throw new NotImplementedException("Can't load a ReefUser by it's username");
    }

    #[\Override]
    public function loadUserByIdentifier(string $identifier): UserInterface
    {
        throw new NotImplementedException("Can't load a ReefUser by it's identifier");
    }
}
