using ClaudeDo.Data;
using ClaudeDo.Data.Models;
using ClaudeDo.Ui.Services;
using ClaudeDo.Ui.ViewModels.Islands;
using Microsoft.EntityFrameworkCore;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Ui.Tests.ViewModels;

/// Covers the worktree-less "list handler" host task (Mission Control's "Let Claude handle
/// it"): it has no WorktreeEntity, so the detail pane's review range must fall back to
/// TaskEntity.HandlerBaseCommit/HandlerHeadCommit, and the merge/diff card must still render.
public class DetailsIslandHandlerRangeTests : IDisposable
{
    private readonly string _dbPath;

    public DetailsIslandHandlerRangeTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_details_handler_test_{Guid.NewGuid():N}.db");
        using var ctx = NewContext();
        ctx.Database.EnsureCreated();
    }

    public void Dispose()
    {
        try { File.Delete(_dbPath); } catch { }
        try { File.Delete(_dbPath + "-wal"); } catch { }
        try { File.Delete(_dbPath + "-shm"); } catch { }
    }

    private ClaudeDoDbContext NewContext()
    {
        var opts = new DbContextOptionsBuilder<ClaudeDoDbContext>()
            .UseSqlite($"Data Source={_dbPath}")
            .Options;
        return new ClaudeDoDbContext(opts);
    }




    private sealed class FakeWorkerClient : StubWorkerClient
    {
        public override bool IsConnected => true;
    }

    private DetailsIslandViewModel BuildVm()
    {
        var factory = new TestDbFactory(NewContext);
        return new DetailsIslandViewModel(
            factory, new FakeWorkerClient(), new NullServiceProvider(), new MergeCoordinator());
    }

    [Fact]
    public async Task Bind_WorktreeLessHandlerTask_FallsBackToHandlerCommitRange_AndShowsMergeSection()
    {
        const string listId = "list-1";
        const string taskId = "handler-task-1";

        await using (var ctx = NewContext())
        {
            ctx.Lists.Add(new ListEntity { Id = listId, Name = "L", WorkingDir = @"C:\repo", CreatedAt = DateTime.UtcNow });
            ctx.Tasks.Add(new TaskEntity
            {
                Number = TestTaskNumbers.Next(),
                Id = taskId, ListId = listId, Title = "List handler: L",
                Status = TaskStatus.WaitingForReview, IsManual = true,
                HandlerBaseCommit = "base123", HandlerHeadCommit = "head456",
                CreatedAt = DateTime.UtcNow,
            });
            await ctx.SaveChangesAsync();
        }

        var vm = BuildVm();
        vm.Bind(new TaskRowViewModel { Id = taskId, Status = TaskStatus.WaitingForReview });

        var deadline = DateTime.UtcNow.AddSeconds(5);
        while (DateTime.UtcNow < deadline && vm.WorktreeBaseCommit is null)
            await Task.Delay(20);

        Assert.Equal("base123", vm.WorktreeBaseCommit);
        Assert.Equal("head456", vm.WorktreeHeadCommit);
        Assert.Null(vm.WorktreePath);
        Assert.True(vm.Merge.ShowMergeSection);
        Assert.True(vm.Merge.HasReviewableDiff);
    }
}
