using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using StellaOps.Concelier.Connector.Common.Http;
using StellaOps.Concelier.Connector.Ics.Kaspersky.Configuration;
using StellaOps.Concelier.Connector.Ics.Kaspersky.Internal;

namespace StellaOps.Concelier.Connector.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.Concelier.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;
    }
}
