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

namespace StellaOps.Feedser.Source.Ics.Kaspersky;

public static class KasperskyServiceCollectionExtensions
{
    public static IServiceCollection AddKasperskyIcsConnector(this IServiceCollection services, Action<KasperskyOptions> configure)
    {
        ArgumentNullException.ThrowIfNull(services);
        ArgumentNullException.ThrowIfNull(configure);

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

        services.AddSourceHttpClient(KasperskyOptions.HttpClientName, (sp, clientOptions) =>
        {
            var options = sp.GetRequiredService<IOptions<KasperskyOptions>>().Value;
            clientOptions.BaseAddress = options.FeedUri;
            clientOptions.Timeout = TimeSpan.FromSeconds(30);
            clientOptions.UserAgent = "StellaOps.Feedser.IcsKaspersky/1.0";
            clientOptions.AllowedHosts.Clear();
            clientOptions.AllowedHosts.Add(options.FeedUri.Host);
            clientOptions.DefaultRequestHeaders["Accept"] = "application/rss+xml";
        });

        services.AddTransient<KasperskyFeedClient>();
        services.AddTransient<KasperskyConnector>();

        return services;
    }
}
