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

namespace ClaudeDo.Worker.Tests.Repositories;

public sealed class TaskRepositoryRoadblockTests : IDisposable
{
    private readonly DbFixture _db = new();
    private readonly ClaudeDoDbContext _ctx;
    private readonly TaskRepository _tasks;
    private readonly ListRepository _lists;

    public TaskRepositoryRoadblockTests()
    {
        _ctx = _db.CreateContext();
        _tasks = new TaskRepository(_ctx);
        _lists = new ListRepository(_ctx);
    }

    public void Dispose()
    {
        _ctx.Dispose();
        _db.Dispose();
    }

    private async Task<string> CreateListAsync()
    {
        var listId = Guid.NewGuid().ToString();
        await _lists.AddAsync(new ListEntity
        {
            Id = listId,
            Name = "Test List",
            CreatedAt = DateTime.UtcNow,
        });
        return listId;
    }

    [Fact]
    public async Task NewTask_HasRoadblockCount_Zero()
    {
        var listId = await CreateListAsync();
        var task = new TaskEntity
        {
            Id = Guid.NewGuid().ToString(),
            ListId = listId,
            Title = "T",
            CreatedAt = DateTime.UtcNow,
            CommitType = "feat",
        };
        await _tasks.AddAsync(task);

        var loaded = await _tasks.GetByIdAsync(task.Id);
        Assert.NotNull(loaded);
        Assert.Equal(0, loaded!.RoadblockCount);
    }

    [Fact]
    public async Task SetRoadblockCountAsync_PersistsCount()
    {
        var listId = await CreateListAsync();
        var task = new TaskEntity
        {
            Id = Guid.NewGuid().ToString(),
            ListId = listId,
            Title = "T",
            CreatedAt = DateTime.UtcNow,
            CommitType = "feat",
        };
        await _tasks.AddAsync(task);

        await _tasks.SetRoadblockCountAsync(task.Id, 2);

        using var readCtx = _db.CreateContext();
        var reloaded = await new TaskRepository(readCtx).GetByIdAsync(task.Id);
        Assert.NotNull(reloaded);
        Assert.Equal(2, reloaded!.RoadblockCount);
    }
}
