using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StellaOps.Concelier.Connector.Common.Http;
using StellaOps.Concelier.Connector.Nvd.Configuration;
using StellaOps.Concelier.Connector.Nvd.Internal;

namespace StellaOps.Concelier.Connector.Nvd;

public static class NvdServiceCollectionExtensions
{
    public static IServiceCollection AddNvdConnector(this IServiceCollection services, Action<NvdOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

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

        services.AddSingleton<NvdDiagnostics>();
        services.AddTransient<NvdConnector>();
        return services;
    }
}
