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

namespace StellaOps.Feedser.Source.Cve;

public static class CveServiceCollectionExtensions
{
    public static IServiceCollection AddCveConnector(this IServiceCollection services, Action<CveOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(CveOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<CveOptions>>().Value;
            clientOptions.BaseAddress = options.BaseEndpoint;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Feedser.Cve/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseEndpoint.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/json";
            if (options.HasCredentials())
            {
                clientOptions.DefaultRequestHeaders["CVE-API-ORG"] = options.ApiOrg;
                clientOptions.DefaultRequestHeaders["CVE-API-USER"] = options.ApiUser;
                clientOptions.DefaultRequestHeaders["CVE-API-KEY"] = options.ApiKey;
            }
        });

        services.AddSingleton<CveDiagnostics>();
        services.AddTransient<CveConnector>();
        return services;
    }
}
