using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.CertCc.Configuration;
using StellaOps.Feedser.Source.CertCc.Internal;
using StellaOps.Feedser.Source.Common.Http;

namespace StellaOps.Feedser.Source.CertCc;

public static class CertCcServiceCollectionExtensions
{
    public static IServiceCollection AddCertCcConnector(this IServiceCollection services, Action<CertCcOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

        services.AddOptions<CertCcOptions>()
            .Configure(configure)
            .PostConfigure(static options => options.Validate());

        services.AddSourceHttpClient(CertCcOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<CertCcOptions>>().Value;
            clientOptions.BaseAddress = options.BaseApiUri;
            clientOptions.UserAgent = "StellaOps.Feedser.CertCc/1.0";
            clientOptions.Timeout = TimeSpan.FromSeconds(20);
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseApiUri.Host);
        });

        services.TryAddSingleton<CertCcSummaryPlanner>();
        services.TryAddSingleton<CertCcDiagnostics>();
        services.AddTransient<CertCcConnector>();
        return services;
    }
}
