using ClaudeDo.Data.Filtering;
using Microsoft.EntityFrameworkCore;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Data.Tests.Filtering;

/// <summary>
/// Proves that <see cref="ClaudeDo.Data.Filtering.TaskListFilter.MatchExpression"/> is a real
/// expression tree that EF Core can translate into SQL, not just an in-memory delegate — the
/// whole point of splitting it out from <c>Matches</c>.
/// </summary>
public sealed class MatchExpressionSqlTests : IDisposable
{
    private readonly string _dbPath;
    private readonly DbContextOptions<ClaudeDoDbContext> _options;

    public MatchExpressionSqlTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_matchexpr_{Guid.NewGuid():N}.db");
        _options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={_dbPath}")
            .Options;

        using var ctx = new ClaudeDoDbContext(_options);
        ctx.Database.EnsureCreated();
    }

    public void Dispose()
    {
        foreach (var suffix in new[] { "", "-wal", "-shm" })
            try { File.Delete(_dbPath + suffix); } catch { }
    }

    [Fact]
    public void StatusFilter_MatchExpression_translates_to_a_SQL_WHERE_on_status()
    {
        var filter = new StatusFilter("virtual:queued", TaskStatus.Queued);

        using var ctx = new ClaudeDoDbContext(_options);
        var sql = ctx.Tasks.Where(filter.MatchExpression).ToQueryString();

        Assert.Contains("WHERE", sql, StringComparison.OrdinalIgnoreCase);
        Assert.Contains("status", sql, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public void UserListFilter_MatchExpression_translates_to_a_SQL_WHERE_on_list_id()
    {
        var filter = new UserListFilter("abc");

        using var ctx = new ClaudeDoDbContext(_options);
        var sql = ctx.Tasks.Where(filter.MatchExpression).ToQueryString();

        Assert.Contains("WHERE", sql, StringComparison.OrdinalIgnoreCase);
        Assert.Contains("list_id", sql, StringComparison.OrdinalIgnoreCase);
    }
}
