using Leanetec.EConnect.Client.Interface;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Leanetec.EConnect.Infrastructure;

public static class DependencyInjection
{
    internal static readonly string EConnectClientName = Guid.NewGuid().ToString();

    internal static IServiceCollection AddEConnectHttpClient(this IServiceCollection services)
    {
        services.AddHttpClient(EConnectClientName, (provider, client) => {
            var opt = provider.GetRequiredService<IOptions<ClientOptions>>().Value;

            // add common parameters
            if (opt.BaseAddress is string baseAddress)
                client.BaseAddress = new Uri(baseAddress);

            if (opt.Timeout is TimeSpan timeout)
                client.Timeout = timeout;

            opt.AfterHttpInit?.Invoke(client);
        });

        return services;
    }

    public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, Action<Config>? options = null)
    {
        Config config = new(services);
        options?.Invoke(config);
        services.AddEConnectHttpClient();
        services.AddScoped(typeof(IEConnectClient<>), typeof(EConnectClient<>));
        return services;
    }

    public sealed class Config
    {
        private readonly IServiceCollection _services;

        internal Config(IServiceCollection services)
        {
            _services = services;
        }

        public void ConfigureClient(IConfiguration config)
        {
            _services.Configure<ClientOptions>(config);
        }

        public void ConfigureClient(Action<ClientOptions> options)
        {
            _services.Configure(options);
        }
    }
}
