using System;
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.Vndr.Msrc.Configuration;
using StellaOps.Feedser.Source.Vndr.Msrc.Internal;

namespace StellaOps.Feedser.Source.Vndr.Msrc;

public static class MsrcServiceCollectionExtensions
{
    public static IServiceCollection AddMsrcConnector(this IServiceCollection services, Action<MsrcOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(MsrcOptions.HttpClientName, static (provider, clientOptions) =>
        {
            var options = provider.GetRequiredService<IOptions<MsrcOptions>>().Value;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseUri.Host);
            clientOptions.AllowedHosts.Add("download.microsoft.com");
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.All;
            };
        });

        services.AddSourceHttpClient(MsrcOptions.TokenClientName, static (_, clientOptions) =>
        {
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add("login.microsoftonline.com");
            clientOptions.ConfigureHandler = handler =>
            {
                handler.AutomaticDecompression = DecompressionMethods.All;
            };
        });

        services.TryAddSingleton<IMsrcTokenProvider, MsrcTokenProvider>();
        services.TryAddSingleton<MsrcApiClient>();
        services.TryAddSingleton<MsrcDetailParser>();
        services.TryAddSingleton<MsrcDiagnostics>();
        services.AddTransient<MsrcConnector>();

        return services;
    }
}
