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

namespace StellaOps.Feedser.Source.Distro.Ubuntu;

public static class UbuntuServiceCollectionExtensions
{
    public static IServiceCollection AddUbuntuConnector(this IServiceCollection services, Action<UbuntuOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(UbuntuOptions.HttpClientName, (sp, httpOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<UbuntuOptions>>().Value;
            httpOptions.BaseAddress = options.NoticesEndpoint.GetLeftPart(UriPartial.Authority) is { Length: > 0 } authority
                ? new Uri(authority)
                : new Uri("https://ubuntu.com/");
            httpOptions.Timeout = options.FetchTimeout;
            httpOptions.UserAgent = options.UserAgent;
            httpOptions.AllowedHosts.Clear();
            httpOptions.AllowedHosts.Add(options.NoticesEndpoint.Host);
            httpOptions.AllowedHosts.Add(options.NoticeDetailBaseUri.Host);
            httpOptions.DefaultRequestHeaders["Accept"] = "application/json";
        });

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