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

namespace StellaOps.Feedser.Source.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.Feedser.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;
    }
}
