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.Vmware.Configuration;

namespace StellaOps.Feedser.Source.Vndr.Vmware;

public static class VmwareServiceCollectionExtensions
{
    public static IServiceCollection AddVmwareConnector(this IServiceCollection services, Action<VmwareOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(VmwareOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<VmwareOptions>>().Value;
            clientOptions.BaseAddress = new Uri(options.IndexUri.GetLeftPart(UriPartial.Authority));
            clientOptions.Timeout = options.HttpTimeout;
            clientOptions.UserAgent = "StellaOps.Feedser.VMware/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.IndexUri.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/json";
        });

        services.TryAddSingleton<VmwareDiagnostics>();
        services.AddTransient<VmwareConnector>();
        services.AddTransient<VmwareFetchJob>();
        services.AddTransient<VmwareParseJob>();
        services.AddTransient<VmwareMapJob>();
        return services;
    }
}
