using ZB.MOM.WW.CBDD.Bson;
using ZB.MOM.WW.CBDD.Shared;

namespace ZB.MOM.WW.CBDD.Tests;

public class InsertBulkTests : IDisposable
{
    private readonly TestDbContext _db;
    private readonly string _testFile;

    /// <summary>
    ///     Initializes a new instance of the <see cref="InsertBulkTests" /> class.
    /// </summary>
    public InsertBulkTests()
    {
        _testFile = Path.GetTempFileName();
        _db = new TestDbContext(_testFile);
    }

    /// <summary>
    ///     Disposes test resources.
    /// </summary>
    public void Dispose()
    {
        _db.Dispose();
    }

    /// <summary>
    ///     Verifies bulk inserts are immediately persisted and visible.
    /// </summary>
    [Fact]
    public void InsertBulk_PersistsData_ImmediatelyVisible()
    {
        var users = new List<User>();
        for (var i = 0; i < 50; i++) users.Add(new User { Id = ObjectId.NewObjectId(), Name = $"User {i}", Age = 20 });

        _db.Users.InsertBulk(users);
        _db.SaveChanges();

        var insertedUsers = _db.Users.FindAll().ToList();

        insertedUsers.Count.ShouldBe(50);
    }

    /// <summary>
    ///     Verifies bulk inserts spanning multiple pages persist correctly.
    /// </summary>
    [Fact]
    public void InsertBulk_SpanningMultiplePages_PersistsCorrectly()
    {
        // 16KB page. User ~50 bytes. 400 users -> ~20KB -> 2 pages.
        var users = new List<User>();
        for (var i = 0; i < 400; i++)
            users.Add(new User
            {
                Id = ObjectId.NewObjectId(),
                Name = $"User {i} with some long padding text to ensure we fill space {new string('x', 50)}", Age = 20
            });

        _db.Users.InsertBulk(users);
        _db.SaveChanges();

        _db.Users.Count().ShouldBe(400);
    }
}