using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.Common.Http;
using StellaOps.Feedser.Source.Vndr.Adobe.Configuration;

namespace StellaOps.Feedser.Source.Vndr.Adobe;

public static class AdobeServiceCollectionExtensions
{
    public static IServiceCollection AddAdobeConnector(this IServiceCollection services, Action<AdobeOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(AdobeOptions.HttpClientName, static (sp, options) =>
        {
            var adobeOptions = sp.GetRequiredService<IOptions<AdobeOptions>>().Value;
            options.BaseAddress = adobeOptions.IndexUri;
            options.UserAgent = "StellaOps.Feedser.VndrAdobe/1.0";
            options.Timeout = TimeSpan.FromSeconds(20);
            options.AllowedHosts.Clear();
            options.AllowedHosts.Add(adobeOptions.IndexUri.Host);
            foreach (var additional in adobeOptions.AdditionalIndexUris)
            {
                options.AllowedHosts.Add(additional.Host);
            }
        });

        services.TryAddSingleton<AdobeDiagnostics>();
        services.AddTransient<AdobeConnector>();
        return services;
    }
}
