using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using WishNinja.Data;

namespace WishNinja.Tests;

/// <summary>
/// An <see cref="IDbContextFactory{TContext}"/> backed by a single shared in-memory SQLite
/// connection, so data written by one context is visible to the next. Dispose to tear down.
/// </summary>
public sealed class TestDb : IDbContextFactory<ApplicationDbContext>, IDisposable
{
    private readonly SqliteConnection _connection;
    private readonly DbContextOptions<ApplicationDbContext> _options;

    public TestDb()
    {
        _connection = new SqliteConnection("DataSource=:memory:");
        _connection.Open();
        _options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseSqlite(_connection)
            .Options;
        using var ctx = CreateDbContext();
        ctx.Database.EnsureCreated();
    }

    public ApplicationDbContext CreateDbContext() => new(_options);

    public void Dispose() => _connection.Dispose();
}
