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.Apple.Internal;

namespace StellaOps.Feedser.Source.Vndr.Apple;

public static class AppleServiceCollectionExtensions
{
    public static IServiceCollection AddAppleConnector(this IServiceCollection services, Action<AppleOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(AppleOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<AppleOptions>>().Value;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Feedser.Apple/1.0";
            clientOptions.AllowedHosts.Clear();
            if (options.SoftwareLookupUri is not null)
            {
                clientOptions.AllowedHosts.Add(options.SoftwareLookupUri.Host);
            }

            if (options.AdvisoryBaseUri is not null)
            {
                clientOptions.AllowedHosts.Add(options.AdvisoryBaseUri.Host);
            }
        });

        services.TryAddSingleton<TimeProvider>(_ => TimeProvider.System);
        services.AddSingleton<AppleDiagnostics>();
        services.AddTransient<AppleConnector>();
        return services;
    }
}
