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.Kev.Configuration;
using StellaOps.Feedser.Source.Kev.Internal;

namespace StellaOps.Feedser.Source.Kev;

public static class KevServiceCollectionExtensions
{
    public static IServiceCollection AddKevConnector(this IServiceCollection services, Action<KevOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

        services.AddOptions<KevOptions>()
            .Configure(configure)
            .PostConfigure(static options => options.Validate());

        services.AddSourceHttpClient(KevOptions.HttpClientName, (provider, clientOptions) =>
        {
            var opts = provider.GetRequiredService<IOptions<KevOptions>>().Value;
            clientOptions.BaseAddress = opts.FeedUri;
            clientOptions.Timeout = opts.RequestTimeout;
            clientOptions.UserAgent = "StellaOps.Feedser.Kev/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(opts.FeedUri.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/json";
        });

        services.TryAddSingleton<KevDiagnostics>();
        services.AddTransient<KevConnector>();

        return services;
    }
}
