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

namespace StellaOps.Feedser.Source.Osv;

public static class OsvServiceCollectionExtensions
{
    public static IServiceCollection AddOsvConnector(this IServiceCollection services, Action<OsvOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(OsvOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<OsvOptions>>().Value;
            clientOptions.BaseAddress = options.BaseUri;
            clientOptions.Timeout = options.HttpTimeout;
            clientOptions.UserAgent = "StellaOps.Feedser.OSV/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.BaseUri.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/zip";
        });

        services.AddSingleton<OsvDiagnostics>();
        services.AddTransient<OsvConnector>();
        services.AddTransient<OsvFetchJob>();
        services.AddTransient<OsvParseJob>();
        services.AddTransient<OsvMapJob>();
        return services;
    }
}
