using ZB.MOM.WW.CBDD.Core.Indexing;
using ZB.MOM.WW.CBDD.Shared;

namespace ZB.MOM.WW.CBDD.Tests;

public class DocumentCollectionIndexApiTests : IDisposable
{
    private readonly string _dbPath;
    private readonly Shared.TestDbContext _db;

    public DocumentCollectionIndexApiTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"collection_index_api_{Guid.NewGuid():N}.db");
        _db = new Shared.TestDbContext(_dbPath);
    }

    [Fact]
    public void CreateVectorIndex_And_DropIndex_Should_Work()
    {
        _db.VectorItems.Insert(new VectorEntity { Title = "A", Embedding = [1f, 1f, 1f] });
        _db.VectorItems.Insert(new VectorEntity { Title = "B", Embedding = [2f, 2f, 2f] });
        _db.SaveChanges();

        _db.VectorItems.CreateVectorIndex(v => v.Embedding, 3, VectorMetric.DotProduct, "idx_vector_extra");

        var indexNames = _db.VectorItems.GetIndexes().Select(x => x.Name).ToList();
        indexNames.ShouldContain("idx_vector_extra");

        _db.VectorItems.DropIndex("idx_vector_extra").ShouldBeTrue();
        _db.VectorItems.DropIndex("idx_vector_extra").ShouldBeFalse();

        _db.VectorItems.GetIndexes().Select(x => x.Name).ShouldNotContain("idx_vector_extra");
    }

    [Fact]
    public void EnsureIndex_Should_Return_Existing_Index_When_Already_Present()
    {
        var first = _db.People.EnsureIndex(p => p.Age, name: "idx_people_age");
        var second = _db.People.EnsureIndex(p => p.Age, name: "idx_people_age");

        ReferenceEquals(first, second).ShouldBeTrue();
    }

    [Fact]
    public void DropIndex_Should_Reject_Primary_Index_Name()
    {
        Should.Throw<InvalidOperationException>(() => _db.People.DropIndex("_id"));
    }

    public void Dispose()
    {
        _db.Dispose();
        if (File.Exists(_dbPath)) File.Delete(_dbPath);
        var wal = Path.ChangeExtension(_dbPath, ".wal");
        if (File.Exists(wal)) File.Delete(wal);
    }
}
