using CashLineERP.Infrastructure.Persistence;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage;

namespace CashLineERP.Api.Tests;

internal static class QaDbContextFactory
{
    private static readonly InMemoryDatabaseRoot SharedDatabaseRoot = new();

    public static CashLineErpDbContext CreateContext()
    {
        var options = new DbContextOptionsBuilder<CashLineErpDbContext>()
            .UseInMemoryDatabase($"CashLineERP-QA-{Guid.NewGuid():N}", SharedDatabaseRoot)
            .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning))
            .Options;

        var dbContext = new CashLineErpDbContext(options);
        dbContext.Database.EnsureDeleted();
        dbContext.Database.EnsureCreated();
        return dbContext;
    }

    public static SqliteConnection CreateOpenSqliteConnection()
    {
        var connection = new SqliteConnection("Data Source=:memory:");
        connection.Open();
        return connection;
    }

    public static CashLineErpDbContext CreateSqliteContext(SqliteConnection connection)
    {
        var options = new DbContextOptionsBuilder<CashLineErpDbContext>()
            .UseSqlite(connection)
            .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning))
            .Options;

        var dbContext = new CashLineErpDbContext(options);
        dbContext.Database.EnsureDeleted();
        dbContext.Database.EnsureCreated();
        return dbContext;
    }
}
