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

namespace StellaOps.Feedser.Source.Acsc;

public static class AcscServiceCollectionExtensions
{
    public static IServiceCollection AddAcscConnector(this IServiceCollection services, Action<AcscOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(AcscOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<AcscOptions>>().Value;
            clientOptions.Timeout = options.RequestTimeout;
            clientOptions.UserAgent = options.UserAgent;
            clientOptions.RequestVersion = options.RequestVersion;
            clientOptions.VersionPolicy = options.VersionPolicy;
            clientOptions.AllowAutoRedirect = true;
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                handler.AllowAutoRedirect = true;
            };

            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseEndpoint.Host);
            if (options.RelayEndpoint is not null)
            {
                clientOptions.AllowedHosts.Add(options.RelayEndpoint.Host);
            }

            clientOptions.DefaultRequestHeaders["Accept"] = string.Join(", ", new[]
            {
                "application/rss+xml",
                "application/atom+xml;q=0.9",
                "application/xml;q=0.8",
                "text/xml;q=0.7",
            });
        });

        services.AddSingleton<AcscDiagnostics>();
        services.AddTransient<AcscConnector>();

        return services;
    }
}
