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

namespace StellaOps.Feedser.Source.Ru.Bdu;

public static class RuBduServiceCollectionExtensions
{
    public static IServiceCollection AddRuBduConnector(this IServiceCollection services, Action<RuBduOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(RuBduOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<RuBduOptions>>().Value;
            clientOptions.BaseAddress = options.BaseAddress;
            clientOptions.Timeout = options.RequestTimeout;
            clientOptions.UserAgent = options.UserAgent;
            clientOptions.AllowAutoRedirect = true;
            clientOptions.DefaultRequestHeaders["Accept-Language"] = options.AcceptLanguage;
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseAddress.Host);
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                handler.AllowAutoRedirect = true;
                handler.UseCookies = true;
                handler.CookieContainer = new CookieContainer();
            };
        });

        services.AddSingleton<RuBduDiagnostics>();
        services.AddTransient<RuBduConnector>();

        return services;
    }
}
