<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Api;

use InPost\International\Http\Client\Factory\ClientFactoryInterface;
use InPost\International\OAuth2\Authentication\ClientCredentialsInterface;
use InPost\International\OAuth2\Authentication\ClientSecretPost;
use InPost\International\OAuth2\AuthorizationProvider;
use InPost\International\OAuth2\AuthorizationProviderFactoryInterface;
use InPost\International\OAuth2\AuthorizationProviderInterface;
use InPost\International\OAuth2\AuthorizationServerClient;
use InPost\International\OAuth2\AuthorizationServerClientInterface;
use InPost\International\OAuth2\Grant\ClientCredentialsGrant;
use InPost\International\OAuth2\Grant\GrantTypeInterface;
use InPost\International\OAuth2\Token\AccessTokenRepositoryInterface;
use InPost\International\OAuth2\UriCollectionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class AuthorizationProviderFactory implements AuthorizationProviderFactoryInterface
{
    /**
     * @var RequestFactoryInterface
     */
    private $requestFactory;

    /**
     * @var StreamFactoryInterface
     */
    private $streamFactory;

    /**
     * @var ClientFactoryInterface
     */
    private $clientFactory;

    /**
     * @var GrantTypeInterface
     */
    private $grantType;

    public function __construct(RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory, ClientFactoryInterface $clientFactory, GrantTypeInterface $grantType = null)
    {
        $this->requestFactory = $requestFactory;
        $this->streamFactory = $streamFactory;
        $this->clientFactory = $clientFactory;
        $this->grantType = $grantType ?? new ClientCredentialsGrant();
    }

    public function create(UriCollectionInterface $uriCollection, ClientCredentialsInterface $credentials, AccessTokenRepositoryInterface $tokenRepository = null): AuthorizationProviderInterface
    {
        $authSeverClient = $this->createAuthServerClient($uriCollection);

        return new AuthorizationProvider(
            $authSeverClient,
            $this->grantType,
            $credentials,
            $tokenRepository
        );
    }

    private function createAuthServerClient(UriCollectionInterface $uriCollection): AuthorizationServerClientInterface
    {
        $httpClient = $this->clientFactory->create();

        return new AuthorizationServerClient(
            $httpClient,
            $this->requestFactory,
            $this->streamFactory,
            $uriCollection,
            new ClientSecretPost()
        );
    }
}
