using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using StellaOps.Feedser.Source.CertFr.Configuration;
using StellaOps.Feedser.Source.CertFr.Internal;
using StellaOps.Feedser.Source.Common.Http;

namespace StellaOps.Feedser.Source.CertFr;

public static class CertFrServiceCollectionExtensions
{
    public static IServiceCollection AddCertFrConnector(this IServiceCollection services, Action<CertFrOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(CertFrOptions.HttpClientName, static (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<CertFrOptions>>().Value;
            clientOptions.BaseAddress = options.FeedUri;
            clientOptions.UserAgent = "StellaOps.Feedser.CertFr/1.0";
            clientOptions.Timeout = TimeSpan.FromSeconds(20);
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.FeedUri.Host);
        });

        services.TryAddSingleton<CertFrFeedClient>();
        services.AddTransient<CertFrConnector>();
        return services;
    }
}
