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.Abstractions;
using StellaOps.Excititor.Connectors.Oracle.CSAF.Configuration;
using StellaOps.Excititor.Connectors.Oracle.CSAF.Metadata;
using StellaOps.Excititor.Core;
using System.IO.Abstractions;

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

public static class OracleConnectorServiceCollectionExtensions
{
    public static IServiceCollection AddOracleCsafConnector(this IServiceCollection services, Action<OracleConnectorOptions>? configure = null)
    {
        ArgumentNullException.ThrowIfNull(services);

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

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

        services.AddSingleton<IVexConnectorOptionsValidator<OracleConnectorOptions>, OracleConnectorOptionsValidator>();

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

        services.AddSingleton<OracleCatalogLoader>();
        services.AddSingleton<IVexConnector, OracleCsafConnector>();

        return services;
    }
}
