using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.Common.Http;
using StellaOps.Feedser.Source.Distro.RedHat.Configuration;

namespace StellaOps.Feedser.Source.Distro.RedHat;

public static class RedHatServiceCollectionExtensions
{
    public static IServiceCollection AddRedHatConnector(this IServiceCollection services, Action<RedHatOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(RedHatOptions.HttpClientName, (sp, httpOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<RedHatOptions>>().Value;
            httpOptions.BaseAddress = options.BaseEndpoint;
            httpOptions.Timeout = options.FetchTimeout;
            httpOptions.UserAgent = options.UserAgent;
            httpOptions.AllowedHosts.Clear();
            httpOptions.AllowedHosts.Add(options.BaseEndpoint.Host);
            httpOptions.DefaultRequestHeaders["Accept"] = "application/json";
        });

        services.AddTransient<RedHatConnector>();
        return services;
    }
}
