<?php
// src/Auth/OIDCProvider.php
namespace App\Auth;

use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;

class OIDCProvider extends AbstractProvider
{
    use BearerAuthorizationTrait;

    public const ACCESS_TOKEN_RESOURCE_OWNER_ID = 'sub';

    protected $url;
    protected $issuer;
    protected $authorizationUrl;
    protected $tokenUrl;
    protected $userInfoUrl;

    public function __construct(array $options = [], array $collaborators = [])
    {
        parent::__construct($options, $collaborators);

        $this->issuer = $options['url'];
        $this->authorizationUrl = $options['authorization_url'] ?? $this->issuer . '/oauth/authorize';
        $this->tokenUrl = $options['token_url'] ?? $this->issuer . '/oauth/token';
        $this->userInfoUrl = $options['userinfo_url'] ?? $this->issuer . '/oauth/userinfo';
    }

    public function getBaseAuthorizationUrl(): string
    {
        return $this->authorizationUrl;
    }

    public function getBaseAccessTokenUrl(array $params): string
    {
        return $this->tokenUrl;
    }

    public function getResourceOwnerDetailsUrl(AccessToken $token): string
    {
        return $this->userInfoUrl;
    }

    protected function getDefaultScopes(): array
    {
        return ['openid', 'profile', 'email'];
    }

    protected function checkResponse(ResponseInterface $response, $data): void
    {
        if (!empty($data['error'])) {
            $message = $data['error'] . ': ' . ($data['error_description'] ?? '');
            throw new IdentityProviderException($message, $response->getStatusCode(), $response);
        }
    }

    protected function createResourceOwner(array $response, AccessToken $token): OIDCResourceOwner
    {
        return new OIDCResourceOwner($response);
    }
}