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

namespace StellaOps.Feedser.Source.Distro.Debian;

public static class DebianServiceCollectionExtensions
{
    public static IServiceCollection AddDebianConnector(this IServiceCollection services, Action<DebianOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

        services.AddOptions<DebianOptions>()
            .Configure(configure)
            .PostConfigure(static options => options.Validate());

        services.AddSourceHttpClient(DebianOptions.HttpClientName, (sp, httpOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<DebianOptions>>().Value;
            httpOptions.BaseAddress = options.DetailBaseUri.GetLeftPart(UriPartial.Authority) is { Length: > 0 } authority
                ? new Uri(authority, UriKind.Absolute)
                : new Uri("https://security-tracker.debian.org/", UriKind.Absolute);
            httpOptions.Timeout = options.FetchTimeout;
            httpOptions.UserAgent = options.UserAgent;
            httpOptions.AllowedHosts.Clear();
            httpOptions.AllowedHosts.Add(options.DetailBaseUri.Host);
            httpOptions.AllowedHosts.Add(options.ListEndpoint.Host);
            httpOptions.DefaultRequestHeaders["Accept"] = "text/html,application/xhtml+xml,text/plain;q=0.9,application/json;q=0.8";
        });

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