using ZB.MOM.WW.CBDD.Bson;
using ZB.MOM.WW.CBDD.Core.Collections;
using ZB.MOM.WW.CBDD.Core.Storage;
using ZB.MOM.WW.CBDD.Core.Transactions;
using ZB.MOM.WW.CBDD.Shared;
using ZB.MOM.WW.CBDD.Shared.TestDbContext_TestDbContext_Mappers;
using Xunit;

namespace ZB.MOM.WW.CBDD.Tests;

public class DocumentCollectionDeleteTests : IDisposable
{
    private readonly string _dbPath;
    private readonly string _walPath;
    private readonly Shared.TestDbContext _dbContext;

    public DocumentCollectionDeleteTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"test_delete_{Guid.NewGuid()}.db");
        _walPath = Path.Combine(Path.GetTempPath(), $"test_delete_{Guid.NewGuid()}.wal");

        _dbContext = new Shared.TestDbContext(_dbPath);
    }

    public void Dispose()
    {
        _dbContext.Dispose();
    }

    [Fact]
    public void Delete_RemovesDocumentAndIndexEntry()
    {
        var user = new User { Id = ObjectId.NewObjectId(), Name = "To Delete", Age = 10 };
        _dbContext.Users.Insert(user);
        _dbContext.SaveChanges();

        // Verify inserted
        _dbContext.Users.FindById(user.Id).ShouldNotBeNull();

        // Delete
        var deleted = _dbContext.Users.Delete(user.Id);
        _dbContext.SaveChanges();

        // Assert
        deleted.ShouldBeTrue("Delete returned false");

        // Verify deleted from storage
        _dbContext.Users.FindById(user.Id).ShouldBeNull();

        // Verify Index is clean (FindAll uses index scan)
        var all = _dbContext.Users.FindAll();
        all.ShouldBeEmpty();
    }

    [Fact]
    public void Delete_NonExistent_ReturnsFalse()
    {
        var id = ObjectId.NewObjectId();
        var deleted = _dbContext.Users.Delete(id);
        _dbContext.SaveChanges();
        deleted.ShouldBeFalse();
    }

    [Fact]
    public void Delete_WithTransaction_CommitsSuccessfully()
    {
        var user = new User { Id = ObjectId.NewObjectId(), Name = "Txn Delete", Age = 20 };
        _dbContext.Users.Insert(user);
        _dbContext.SaveChanges();

        using (var txn = _dbContext.BeginTransaction())
        {
            _dbContext.Users.Delete(user.Id);
            _dbContext.SaveChanges();
        }

        // Verify
        _dbContext.Users.FindById(user.Id).ShouldBeNull();
    }
}
