using System.Data.Common;
using eSuite.Core.Clock;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Database.Audit.UnitTests.Helpers;

public class TestDbContextFactory : IDisposable
{
    //private const string _connectionString = "Data Source = InMemorySample; Mode=Memory;Cache=Shared";
    private const string _connectionString = "DataSource=:memory:";

    private DbConnection _connection = null!;

    private DbContextOptions<TestDbContext> CreateOptions()
    {
        return new DbContextOptionsBuilder<TestDbContext>()
            .UseSqlite(_connection).Options;
    }

    public TestDbContext CreateContext( IClock clock)
    {
        if (_connection == null)
        {
            _connection = new SqliteConnection(_connectionString);
            _connection.Open();

            var options = CreateOptions();
            using var context = new TestDbContext(options, clock);
            context.Database.EnsureCreated();
        }

        return new TestDbContext(CreateOptions(), clock);
    }

    public void Dispose()
    {
        if (_connection != null)
        {
            _connection.Dispose();
            _connection = null!;
        }
        GC.SuppressFinalize(this);
    }
}