using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Concelier.Connector.Common.Http;
using StellaOps.Concelier.Connector.Vndr.Oracle.Configuration;
using StellaOps.Concelier.Connector.Vndr.Oracle.Internal;

namespace StellaOps.Concelier.Connector.Vndr.Oracle;

public static class OracleServiceCollectionExtensions
{
    public static IServiceCollection AddOracleConnector(this IServiceCollection services, Action<OracleOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

        services.AddOptions<OracleOptions>()
            .Configure(configure)
            .PostConfigure(static opts => opts.Validate());

        services.AddSourceHttpClient(OracleOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<OracleOptions>>().Value;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Concelier.Oracle/1.0";
            clientOptions.AllowedHosts.Clear();
            foreach (var uri in options.AdvisoryUris)
            {
                clientOptions.AllowedHosts.Add(uri.Host);
            }
            foreach (var uri in options.CalendarUris)
            {
                clientOptions.AllowedHosts.Add(uri.Host);
            }
        });

        services.AddTransient<OracleCalendarFetcher>();
        services.AddTransient<OracleConnector>();
        return services;
    }
}
