using ClaudeDo.Data.Models;
using ClaudeDo.Data.Repositories;
using ClaudeDo.Worker.Tests.Infrastructure;

namespace ClaudeDo.Worker.Tests.Repositories;

public class DailyNoteRepositoryTests : IDisposable
{
    private readonly DbFixture _db = new();
    public void Dispose() => _db.Dispose();

    [Fact]
    public async Task Add_AssignsIncrementingSortOrder_WithinDay()
    {
        var day = new DateOnly(2026, 6, 1);
        using (var ctx = _db.CreateContext())
        {
            var repo = new DailyNoteRepository(ctx);
            await repo.AddAsync(day, "first");
            await repo.AddAsync(day, "second");
        }
        using var read = _db.CreateContext();
        var notes = await new DailyNoteRepository(read).ListByDayAsync(day);
        Assert.Equal(new[] { "first", "second" }, notes.Select(n => n.Text));
        Assert.Equal(new[] { 0, 1 }, notes.Select(n => n.SortOrder));
    }

    [Fact]
    public async Task ListBetween_ReturnsOnlyInRange_OrderedByDateThenSort()
    {
        using (var ctx = _db.CreateContext())
        {
            var repo = new DailyNoteRepository(ctx);
            await repo.AddAsync(new DateOnly(2026, 5, 31), "before");
            await repo.AddAsync(new DateOnly(2026, 6, 1), "in-a");
            await repo.AddAsync(new DateOnly(2026, 6, 2), "in-b");
            await repo.AddAsync(new DateOnly(2026, 6, 5), "after");
        }
        using var read = _db.CreateContext();
        var notes = await new DailyNoteRepository(read)
            .ListBetweenAsync(new DateOnly(2026, 6, 1), new DateOnly(2026, 6, 2));
        Assert.Equal(new[] { "in-a", "in-b" }, notes.Select(n => n.Text));
    }

    [Fact]
    public async Task Update_And_Delete_Work()
    {
        var day = new DateOnly(2026, 6, 1);
        string id;
        using (var ctx = _db.CreateContext())
        {
            var n = await new DailyNoteRepository(ctx).AddAsync(day, "orig");
            id = n.Id;
        }
        using (var ctx = _db.CreateContext())
            await new DailyNoteRepository(ctx).UpdateAsync(id, "edited");
        using (var ctx = _db.CreateContext())
        {
            var notes = await new DailyNoteRepository(ctx).ListByDayAsync(day);
            Assert.Equal("edited", notes.Single().Text);
        }
        using (var ctx = _db.CreateContext())
            await new DailyNoteRepository(ctx).DeleteAsync(id);
        using var read = _db.CreateContext();
        Assert.Empty(await new DailyNoteRepository(read).ListByDayAsync(day));
    }
}
