using Autofac;
using Insight.Database;
using PlanTempus.Core.Configurations;
using PlanTempus.Core.Configurations.JsonConfigProvider;
using PlanTempus.Core.Configurations.SmartConfigProvider;
using PlanTempus.Core.Database.ConnectionFactory;
using Shouldly;

namespace PlanTempus.X.TDD.ConfigurationTests;

[TestClass]
public class SmartConfigProviderTests : TestFixture
{
    private const string _testFolder = "ConfigurationTests/";

    [TestMethod]
    public void TrySmartConfigWithOptionsForPostgres()
    {
        var config = new ConfigurationBuilder()
            .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
            .AddSmartConfig(options => options.UsePostgres("DefaultConnection"))
            .Build();

        var actualFeature = config.Get<bool>("Database:UseSSL");
    }

    [TestMethod]
    public void Get_ShouldReturnCorrectValueAsBool()
    {
        // Arrange
        var expectedFeature = true;

        var config = new ConfigurationBuilder()
            .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
            .AddSmartConfig(options => options.UsePostgres("DefaultConnection"))
            .Build();

        // Act
        var actualFeature = config.Get<bool>("Database:UseSSL");

        // Assert
        actualFeature.ShouldBe(expectedFeature);
    }

    [TestMethod]
    public void Get_ShouldReturnCorrectValueWhenSelectingIntoValueRowInConfigTable()
    {
        // Arrange
        var expectedFeature = 100;

        var builder = new ConfigurationBuilder()
            .AddJsonFile($"{_testFolder}appconfiguration.dev.json")
            .AddSmartConfig(options => options.UsePostgres("DefaultConnection"))
            .Build();

        // Act
        var actualFeature = builder.GetSection("Logging:FileOptions").Get<int>("MaxSizeMB");
        var withoutSectionThisAlsoWorks = builder.Get<int>("Logging:FileOptions:MaxSizeMB");

        // Assert
        actualFeature.ShouldBe(expectedFeature);
        actualFeature.ShouldBe(withoutSectionThisAlsoWorks);
    }

    [TestMethod]
    public void TryGetActiveConfigurations()
    {
        var connFactory = Container.Resolve<IDbConnectionFactory>();

        const string sql = @"
            SELECT id, ""key"", value, label, content_type, 
                   valid_from, expires_at, created_at, modified_at, etag 
            FROM app_configuration 
            WHERE CURRENT_TIMESTAMP BETWEEN valid_from AND expires_at
               OR (valid_from IS NULL AND expires_at IS NULL)";

        using (var conn = connFactory.Create())
        {
            var result = conn.QuerySql(sql);
        }
    }
}