using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.Common.Http;
using StellaOps.Feedser.Source.Vndr.Oracle.Configuration;
using StellaOps.Feedser.Source.Vndr.Oracle.Internal;

namespace StellaOps.Feedser.Source.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.Feedser.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;
    }
}
