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

namespace StellaOps.Feedser.Source.Ru.Nkcki;

public static class RuNkckiServiceCollectionExtensions
{
    public static IServiceCollection AddRuNkckiConnector(this IServiceCollection services, Action<RuNkckiOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(RuNkckiOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<RuNkckiOptions>>().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.TryAddSingleton<RuNkckiDiagnostics>();
        services.AddTransient<RuNkckiConnector>();

        return services;
    }
}
