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

namespace ClaudeDo.Worker.Tests.Repositories;

public sealed class MaxTurnsRoundTripTests : IDisposable
{
    private readonly DbFixture _db = new();

    public void Dispose() => _db.Dispose();

    [Fact]
    public async Task ListConfig_persists_max_turns()
    {
        var listId = Guid.NewGuid().ToString();
        using (var ctx = _db.CreateContext())
        {
            await new ListRepository(ctx).AddAsync(new ListEntity
            {
                Id = listId, Name = "L", CreatedAt = DateTime.UtcNow,
            });
        }

        using (var ctx = _db.CreateContext())
        {
            await new ListRepository(ctx).SetConfigAsync(new ListConfigEntity
            {
                ListId = listId, MaxTurns = 42,
            });
        }

        using var readCtx = _db.CreateContext();
        var config = await new ListRepository(readCtx).GetConfigAsync(listId);
        Assert.NotNull(config);
        Assert.Equal(42, config!.MaxTurns);
    }

    [Fact]
    public async Task Task_agent_settings_persist_and_clear_max_turns()
    {
        var listId = Guid.NewGuid().ToString();
        var taskId = Guid.NewGuid().ToString();
        using (var ctx = _db.CreateContext())
        {
            await new ListRepository(ctx).AddAsync(new ListEntity
            {
                Id = listId, Name = "L", CreatedAt = DateTime.UtcNow,
            });
            await new TaskRepository(ctx).AddAsync(new TaskEntity
            {
                Id = taskId, ListId = listId, Title = "t", CreatedAt = DateTime.UtcNow,
            });
        }

        using (var ctx = _db.CreateContext())
        {
            await new TaskRepository(ctx).UpdateAgentSettingsAsync(taskId, null, null, null, maxTurns: 7);
        }

        using (var ctx = _db.CreateContext())
        {
            var entity = await new TaskRepository(ctx).GetByIdAsync(taskId);
            Assert.NotNull(entity);
            Assert.Equal(7, entity!.MaxTurns);
        }

        using (var ctx = _db.CreateContext())
        {
            await new TaskRepository(ctx).UpdateAgentSettingsAsync(taskId, null, null, null, maxTurns: null);
        }

        using var readCtx = _db.CreateContext();
        var final = await new TaskRepository(readCtx).GetByIdAsync(taskId);
        Assert.NotNull(final);
        Assert.Null(final!.MaxTurns);
    }
}
