<?php

/**
 * Chill is a software for social workers.
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;

use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;

class OnBehalfOfUserHttpClient
{
    use BearerAuthorizationTrait;

    private readonly HttpClientInterface $decoratedClient;

    public function __construct(private readonly OnBehalfOfUserTokenStorage $tokenStorage, ?HttpClientInterface $decoratedClient = null)
    {
        $this->decoratedClient = $decoratedClient ?? \Symfony\Component\HttpClient\HttpClient::create();
    }

    public function request(string $method, string $url, array $options = []): ResponseInterface
    {
        $options['headers'] = array_merge(
            $options['headers'] ?? [],
            $this->getAuthorizationHeaders($this->tokenStorage->getToken())
        );
        $options['base_uri'] = 'https://graph.microsoft.com/v1.0/';

        switch ($method) {
            case 'GET':
            case 'HEAD':
                $options['headers']['Accept'] = 'application/json';

                break;

            case 'POST':
            case 'PUT':
            case 'PATCH':
                $options['headers']['Content-Type'] = 'application/json';

                break;

            default:
                throw new \LogicException("Method not supported: {$method}");
        }

        return $this->decoratedClient->request($method, $url, $options);
    }

    public function stream($responses, ?float $timeout = null): ResponseStreamInterface
    {
        return $this->decoratedClient->stream($responses, $timeout);
    }
}
