using IdokladSdk;
using IdokladSdk.Builders;
using Idoklad.Configuration;
using Idoklad.Credentials;

namespace Idoklad.Client;

/// <summary>
/// Builds <see cref="DokladApi"/> instances from resolved per-request credentials, using the
/// official iDoklad .NET SDK (IdokladSdk) and an <see cref="IHttpClientFactory"/>-managed
/// <see cref="HttpClient"/>. This is the iDoklad analogue of microsoft-365-service's graph_client.
/// </summary>
public sealed class DokladApiFactory
{
    public const string HttpClientName = "IdokladApi";

    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IdokladSettings _settings;

    public DokladApiFactory(IHttpClientFactory httpClientFactory, IdokladSettings settings)
    {
        _httpClientFactory = httpClientFactory;
        _settings = settings;
    }

    public DokladApi Create(IdokladCredentials credentials)
    {
        var httpClient = _httpClientFactory.CreateClient(HttpClientName);

        var builder = new DokladApiBuilder(_settings.AppName, _settings.AppVersion)
            .AddClientCredentialsAuthentication(credentials.ClientId, credentials.ClientSecret, credentials.ApplicationId)
            .AddHttpClient(httpClient)
            .AddApiContextOptions(options => options.Language = credentials.Language);

        if (_settings.HasCustomUrls)
        {
            builder = builder.AddCustomApiUrls(_settings.ApiUrl, _settings.IdentityServerUrl);
        }

        return builder.Build();
    }
}
