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

namespace ClaudeDo.Worker.Tests.External;

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

    public ConfigMcpToolsTests()
    {
        _ctx = _db.CreateContext();
        _lists = new ListRepository(_ctx);
        _tasks = new TaskRepository(_ctx);
        _sut = new ConfigMcpTools(_lists, _tasks, new HubBroadcaster(new CapturingHubContext()));
    }

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

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

    [Fact]
    public async Task SetAndGetListConfig_RoundTrips()
    {
        var listId = await SeedListAsync();

        await _sut.SetListConfig(listId, "sonnet", "be terse", null, 42, CancellationToken.None);
        var cfg = await _sut.GetListConfig(listId, CancellationToken.None);

        Assert.NotNull(cfg);
        Assert.Equal("sonnet", cfg!.Model);
        Assert.Equal("be terse", cfg.SystemPrompt);
        Assert.Null(cfg.AgentPath);
        Assert.Equal(42, cfg.MaxTurns);
    }

    [Fact]
    public async Task SetListConfig_AllNull_ClearsConfig()
    {
        var listId = await SeedListAsync();
        await _sut.SetListConfig(listId, "sonnet", null, null, null, CancellationToken.None);

        await _sut.SetListConfig(listId, null, null, null, null, CancellationToken.None);

        Assert.Null(await _sut.GetListConfig(listId, CancellationToken.None));
    }

    [Fact]
    public async Task SetTaskConfig_PersistsOverrides()
    {
        var listId = await SeedListAsync();
        var task = new TaskEntity
        {
            Id = Guid.NewGuid().ToString(),
            ListId = listId,
            Title = "t",
            Status = ClaudeDo.Data.Models.TaskStatus.Idle,
            CreatedAt = DateTime.UtcNow,
            CommitType = "chore",
        };
        await _tasks.AddAsync(task);

        await _sut.SetTaskConfig(task.Id, "opus", null, null, 15, CancellationToken.None);

        var loaded = await _tasks.GetByIdAsync(task.Id);
        Assert.Equal("opus", loaded!.Model);
        Assert.Equal(15, loaded.MaxTurns);
    }
}
