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

namespace StellaOps.Concelier.Connector.Jvn;

public static class JvnServiceCollectionExtensions
{
    public static IServiceCollection AddJvnConnector(this IServiceCollection services, Action<JvnOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(JvnOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<JvnOptions>>().Value;
            clientOptions.BaseAddress = options.BaseEndpoint;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Concelier.Jvn/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseEndpoint.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/xml";
        });

        services.AddTransient<MyJvnClient>();
        services.AddTransient<JvnConnector>();

        return services;
    }
}
