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

namespace StellaOps.Feedser.Source.CertIn;

public static class CertInServiceCollectionExtensions
{
    public static IServiceCollection AddCertInConnector(this IServiceCollection services, Action<CertInOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

        services.AddOptions<CertInOptions>()
            .Configure(configure)
            .PostConfigure(static opts => opts.Validate());

        services.AddSourceHttpClient(CertInOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<CertInOptions>>().Value;
            clientOptions.BaseAddress = options.AlertsEndpoint;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Feedser.CertIn/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.AlertsEndpoint.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/json";
        });

        services.AddTransient<CertInClient>();
        services.AddTransient<CertInConnector>();

        return services;
    }
}
