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

namespace StellaOps.Feedser.Source.Kisa;

public static class KisaServiceCollectionExtensions
{
    public static IServiceCollection AddKisaConnector(this IServiceCollection services, Action<KisaOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(KisaOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<KisaOptions>>().Value;
            clientOptions.Timeout = options.RequestTimeout;
            clientOptions.UserAgent = "StellaOps.Feedser.Kisa/1.0";
            clientOptions.DefaultRequestHeaders["Accept-Language"] = "ko-KR";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.FeedUri.Host);
            clientOptions.AllowedHosts.Add(options.DetailApiUri.Host);
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.All;
                handler.AllowAutoRedirect = true;
            };
        });

        services.TryAddSingleton<HtmlContentSanitizer>();
        services.TryAddSingleton<KisaFeedClient>();
        services.TryAddSingleton<KisaDetailParser>();
        services.AddSingleton<KisaDiagnostics>();
        services.AddTransient<KisaConnector>();
        return services;
    }
}
