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

namespace StellaOps.Feedser.Source.Distro.Suse;

public static class SuseServiceCollectionExtensions
{
    public static IServiceCollection AddSuseConnector(this IServiceCollection services, Action<SuseOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(SuseOptions.HttpClientName, (sp, httpOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<SuseOptions>>().Value;
            httpOptions.BaseAddress = new Uri(options.AdvisoryBaseUri.GetLeftPart(UriPartial.Authority), UriKind.Absolute);
            httpOptions.Timeout = options.FetchTimeout;
            httpOptions.UserAgent = options.UserAgent;
            httpOptions.AllowedHosts.Clear();
            httpOptions.AllowedHosts.Add(options.AdvisoryBaseUri.Host);
            httpOptions.AllowedHosts.Add(options.ChangesEndpoint.Host);
            httpOptions.DefaultRequestHeaders["Accept"] = "text/csv,application/json;q=0.9,text/plain;q=0.8";
        });

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