using Microsoft.Extensions.Configuration;
using ZB.MOM.WW.LmxProxy.Client;

namespace ZB.MOM.WW.LmxProxy.Client.IntegrationTests;

public abstract class IntegrationTestBase : IAsyncLifetime
{
    protected IConfiguration Configuration { get; }
    protected string Host { get; }
    protected int Port { get; }
    protected string ReadWriteApiKey { get; }
    protected string ReadOnlyApiKey { get; }
    protected string InvalidApiKey { get; }
    protected LmxProxyClient? Client { get; set; }

    protected IntegrationTestBase()
    {
        Configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.test.json")
            .Build();

        var section = Configuration.GetSection("LmxProxy");
        Host = section["Host"] ?? "10.100.0.48";
        Port = int.Parse(section["Port"] ?? "50052");
        ReadWriteApiKey = section["ReadWriteApiKey"] ?? throw new Exception("ReadWriteApiKey not configured");
        ReadOnlyApiKey = section["ReadOnlyApiKey"] ?? throw new Exception("ReadOnlyApiKey not configured");
        InvalidApiKey = section["InvalidApiKey"] ?? "invalid-key";
    }

    protected LmxProxyClient CreateClient(string? apiKey = null)
    {
        return new LmxProxyClientBuilder()
            .WithHost(Host)
            .WithPort(Port)
            .WithApiKey(apiKey ?? ReadWriteApiKey)
            .WithTimeout(TimeSpan.FromSeconds(10))
            .WithRetryPolicy(2, TimeSpan.FromSeconds(1))
            .WithMetrics()
            .Build();
    }

    public virtual async Task InitializeAsync()
    {
        Client = CreateClient();
        await Client.ConnectAsync();
    }

    public virtual async Task DisposeAsync()
    {
        if (Client is not null)
        {
            await Client.DisconnectAsync();
            Client.Dispose();
        }
    }
}
