using Csob.Configuration;
using Csob.Credentials;

namespace Csob.Client;

/// <summary>
/// Scoped accessor that resolves the credentials for the current request and lazily builds a
/// single <see cref="CsobApiClient"/> (bound to the request's mutual-TLS client) shared by all
/// services handling that request.
/// </summary>
public sealed class CsobApiAccessor
{
    private readonly RequestCredentialsProvider _credentialsProvider;
    private readonly CsobHttpClientProvider _httpClientProvider;
    private readonly CsobSettings _settings;
    private CsobApiClient? _client;

    public CsobApiAccessor(
        RequestCredentialsProvider credentialsProvider,
        CsobHttpClientProvider httpClientProvider,
        CsobSettings settings)
    {
        _credentialsProvider = credentialsProvider;
        _httpClientProvider = httpClientProvider;
        _settings = settings;
    }

    public CsobApiClient Client
    {
        get
        {
            if (_client is null)
            {
                var credentials = _credentialsProvider.Resolve();
                var http = _httpClientProvider.GetClient(credentials.Certificate!);
                _client = new CsobApiClient(http, credentials, _settings);
            }

            return _client;
        }
    }
}
