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

namespace StellaOps.Feedser.Source.Ghsa;

public static class GhsaServiceCollectionExtensions
{
    public static IServiceCollection AddGhsaConnector(this IServiceCollection services, Action<GhsaOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(GhsaOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<GhsaOptions>>().Value;
            clientOptions.BaseAddress = options.BaseEndpoint;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Feedser.Ghsa/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseEndpoint.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/vnd.github+json";
            clientOptions.DefaultRequestHeaders["Authorization"] = $"Bearer {options.ApiToken}";
            clientOptions.DefaultRequestHeaders["X-GitHub-Api-Version"] = "2022-11-28";
        });

        services.AddSingleton<GhsaDiagnostics>();
        services.AddTransient<GhsaConnector>();
        return services;
    }
}
