using ZB.MOM.WW.CBDD.Shared;

namespace ZB.MOM.WW.CBDD.Tests;

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

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

    [Fact]
    public void SpatialIndex_Should_Handle_Node_Splits_And_Queries()
    {
        const int count = 350;

        for (int i = 0; i < count; i++)
        {
            _db.GeoItems.Insert(new GeoEntity
            {
                Name = $"pt-{i}",
                Location = (40.0 + (i * 0.001), -73.0 - (i * 0.001))
            });
        }

        _db.SaveChanges();

        var all = _db.GeoItems.Within("idx_spatial", (39.5, -74.5), (40.5, -72.5)).ToList();
        all.Count.ShouldBe(count);

        var subset = _db.GeoItems.Within("idx_spatial", (40.05, -73.30), (40.25, -73.05)).ToList();
        subset.Count.ShouldBeGreaterThan(0);
        subset.Count.ShouldBeLessThan(count);

        var near = _db.GeoItems.Near("idx_spatial", (40.10, -73.10), 30.0).ToList();
        near.Count.ShouldBeGreaterThan(0);
    }

    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);
    }
}
