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

namespace StellaOps.Feedser.Source.Vndr.Chromium;

public static class ChromiumServiceCollectionExtensions
{
    public static IServiceCollection AddChromiumConnector(this IServiceCollection services, Action<ChromiumOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSingleton(static sp => sp.GetRequiredService<IOptions<ChromiumOptions>>().Value);

        services.AddSourceHttpClient(ChromiumOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<ChromiumOptions>>().Value;
            clientOptions.BaseAddress = new Uri(options.FeedUri.GetLeftPart(UriPartial.Authority));
            clientOptions.Timeout = TimeSpan.FromSeconds(20);
            clientOptions.UserAgent = "StellaOps.Feedser.VndrChromium/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.FeedUri.Host);
        });

        services.AddSingleton<ChromiumDiagnostics>();
        services.AddTransient<ChromiumFeedLoader>();
        services.AddTransient<ChromiumConnector>();
        return services;
    }
}
