using System.Net;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using StellaOps.Excititor.Connectors.RedHat.CSAF.Configuration;
using StellaOps.Excititor.Connectors.RedHat.CSAF.Metadata;
using StellaOps.Excititor.Core;
using StellaOps.Excititor.Storage.Mongo;
using System.IO.Abstractions;

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

public static class RedHatConnectorServiceCollectionExtensions
{
    public static IServiceCollection AddRedHatCsafConnector(this IServiceCollection services, Action<RedHatConnectorOptions>? configure = null)
    {
        ArgumentNullException.ThrowIfNull(services);

        services.AddOptions<RedHatConnectorOptions>()
            .Configure(options =>
            {
                configure?.Invoke(options);
            })
            .PostConfigure(options => options.Validate());

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

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

        services.AddSingleton<RedHatProviderMetadataLoader>();
        services.AddSingleton<IVexConnector, RedHatCsafConnector>();

        return services;
    }
}
