using System;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.CertBund.Configuration;
using StellaOps.Feedser.Source.CertBund.Internal;
using StellaOps.Feedser.Source.Common.Html;
using StellaOps.Feedser.Source.Common.Http;

namespace StellaOps.Feedser.Source.CertBund;

public static class CertBundServiceCollectionExtensions
{
    public static IServiceCollection AddCertBundConnector(this IServiceCollection services, Action<CertBundOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(CertBundOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<CertBundOptions>>().Value;
            clientOptions.Timeout = options.RequestTimeout;
            clientOptions.UserAgent = "StellaOps.Feedser.CertBund/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.FeedUri.Host);
            clientOptions.AllowedHosts.Add(options.DetailApiUri.Host);
            clientOptions.AllowedHosts.Add(options.PortalBootstrapUri.Host);
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.All;
                handler.UseCookies = true;
                handler.CookieContainer = new System.Net.CookieContainer();
            };
        });

        services.TryAddSingleton<HtmlContentSanitizer>();
        services.TryAddSingleton<CertBundDiagnostics>();
        services.TryAddSingleton<CertBundFeedClient>();
        services.TryAddSingleton<CertBundDetailParser>();
        services.AddTransient<CertBundConnector>();
        return services;
    }
}
