using System;
using System.Net;
using System.Net.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using StellaOps.Excititor.Connectors.MSRC.CSAF.Authentication;
using StellaOps.Excititor.Connectors.MSRC.CSAF.Configuration;
using System.IO.Abstractions;

namespace StellaOps.Excititor.Connectors.MSRC.CSAF.DependencyInjection;

public static class MsrcConnectorServiceCollectionExtensions
{
    public static IServiceCollection AddMsrcCsafConnector(this IServiceCollection services, Action<MsrcConnectorOptions>? configure = null)
    {
        ArgumentNullException.ThrowIfNull(services);

        services.TryAddSingleton<IMemoryCache, MemoryCache>();
        services.TryAddSingleton<IFileSystem, FileSystem>();

        services.AddOptions<MsrcConnectorOptions>()
            .Configure(options => configure?.Invoke(options));

        services.AddHttpClient(MsrcConnectorOptions.TokenClientName, client =>
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                client.DefaultRequestHeaders.UserAgent.ParseAdd("StellaOps.Excititor.Connectors.MSRC.CSAF/1.0");
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
            })
            .ConfigurePrimaryHttpMessageHandler(static () => new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.All,
            });

        services.AddSingleton<IMsrcTokenProvider, MsrcTokenProvider>();

        return services;
    }
}
