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

namespace ClaudeDo.Worker.Tests.UiSchema;

public class TaskEntityFlagsTests : IDisposable
{
    private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo-flags-{Guid.NewGuid():N}.db");

    private ClaudeDoDbContext NewContext()
    {
        var opts = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={_dbPath}")
            .Options;
        var ctx = new ClaudeDoDbContext(opts);
        ctx.Database.EnsureCreated();
        return ctx;
    }

    [Fact]
    public async Task Persists_IsStarred_IsMyDay_And_Notes()
    {
        await using var ctx = NewContext();
        var list = new ListEntity { Id = "l1", Name = "L", CreatedAt = DateTime.UtcNow };
        ctx.Lists.Add(list);
        ctx.Tasks.Add(new TaskEntity
        {
            Id = "t1", ListId = "l1", Title = "T", CreatedAt = DateTime.UtcNow,
            IsStarred = true, IsMyDay = true, Notes = "hello"
        });
        await ctx.SaveChangesAsync();

        await using var ctx2 = NewContext();
        var loaded = await ctx2.Tasks.SingleAsync();
        Assert.True(loaded.IsStarred);
        Assert.True(loaded.IsMyDay);
        Assert.Equal("hello", loaded.Notes);
    }

    [Fact]
    public async Task Defaults_Are_False_And_Null_When_Not_Set()
    {
        await using var ctx = NewContext();
        var list = new ListEntity { Id = "l1", Name = "L", CreatedAt = DateTime.UtcNow };
        ctx.Lists.Add(list);
        ctx.Tasks.Add(new TaskEntity
        {
            Id = "t2", ListId = "l1", Title = "T", CreatedAt = DateTime.UtcNow,
        });
        await ctx.SaveChangesAsync();

        await using var ctx2 = NewContext();
        var loaded = await ctx2.Tasks.SingleAsync();
        Assert.False(loaded.IsStarred);
        Assert.False(loaded.IsMyDay);
        Assert.Null(loaded.Notes);
    }

    public void Dispose()
    {
        try { if (File.Exists(_dbPath)) File.Delete(_dbPath); } catch { }
        try { if (File.Exists(_dbPath + "-wal")) File.Delete(_dbPath + "-wal"); } catch { }
        try { if (File.Exists(_dbPath + "-shm")) File.Delete(_dbPath + "-shm"); } catch { }
    }
}
