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

namespace ClaudeDo.Worker.Tests.Repositories;

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

    public ListRepositoryTests()
    {
        _ctx = _db.CreateContext();
        _lists = new ListRepository(_ctx);
    }

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

    [Fact]
    public async Task AddAsync_And_GetByIdAsync_Roundtrips()
    {
        var entity = new ListEntity
        {
            Id = Guid.NewGuid().ToString(),
            Name = "Shopping",
            CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
            WorkingDir = @"C:\Repos\Test",
            DefaultCommitType = "feat",
        };

        await _lists.AddAsync(entity);
        var loaded = await _lists.GetByIdAsync(entity.Id);

        Assert.NotNull(loaded);
        Assert.Equal(entity.Id, loaded.Id);
        Assert.Equal(entity.Name, loaded.Name);
        Assert.Equal(entity.WorkingDir, loaded.WorkingDir);
        Assert.Equal(entity.DefaultCommitType, loaded.DefaultCommitType);
    }

    [Fact]
    public async Task UpdateAsync_Changes_Fields()
    {
        var entity = new ListEntity
        {
            Id = Guid.NewGuid().ToString(),
            Name = "Original",
            CreatedAt = DateTime.UtcNow,
        };
        await _lists.AddAsync(entity);

        entity.Name = "Updated";
        entity.WorkingDir = @"C:\New";
        await _lists.UpdateAsync(entity);

        var loaded = await _lists.GetByIdAsync(entity.Id);
        Assert.Equal("Updated", loaded!.Name);
        Assert.Equal(@"C:\New", loaded.WorkingDir);
    }

    [Fact]
    public async Task DeleteAsync_Removes_List()
    {
        var entity = new ListEntity
        {
            Id = Guid.NewGuid().ToString(),
            Name = "ToDelete",
            CreatedAt = DateTime.UtcNow,
        };
        await _lists.AddAsync(entity);
        await _lists.DeleteAsync(entity.Id);

        var loaded = await _lists.GetByIdAsync(entity.Id);
        Assert.Null(loaded);
    }

    [Fact]
    public async Task GetAllAsync_Returns_All_Lists()
    {
        var a = new ListEntity { Id = Guid.NewGuid().ToString(), Name = "A", CreatedAt = DateTime.UtcNow.AddMinutes(-1) };
        var b = new ListEntity { Id = Guid.NewGuid().ToString(), Name = "B", CreatedAt = DateTime.UtcNow };
        await _lists.AddAsync(a);
        await _lists.AddAsync(b);

        var all = await _lists.GetAllAsync();
        Assert.True(all.Count >= 2);
    }

}
