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;

public class DetailsIslandDeleteTaskTests : IDisposable
{
    private readonly string _dbPath;

    public DetailsIslandDeleteTaskTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_delete_task_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 RecordingWorkerClient : StubWorkerClient
    {
        public override bool IsConnected { get; } = true;
        public (bool Ok, string? Error) Result { get; set; } = (true, null);
        public string? DeletedTaskId { get; private set; }
        public Exception? ThrowOnDelete { get; set; }

        public RecordingWorkerClient(bool isConnected = true) => IsConnected = isConnected;

        public override Task<(bool Ok, string? Error)> DeleteTaskAsync(string taskId)
        {
            if (ThrowOnDelete != null) throw ThrowOnDelete;
            DeletedTaskId = taskId;
            return Task.FromResult(Result);
        }
    }

    private DetailsIslandViewModel BuildVm(RecordingWorkerClient worker)
    {
        var factory = new TestDbFactory(NewContext);
        return new DetailsIslandViewModel(factory, worker, new NullServiceProvider(), new ClaudeDo.Ui.Services.MergeCoordinator());
    }

    [Fact]
    public async Task DeleteTask_Succeeds_RemovesFromListAndClosesDetail()
    {
        var worker = new RecordingWorkerClient { Result = (true, null) };
        var vm = BuildVm(worker);
        vm.Bind(new TaskRowViewModel { Id = "task-del-1", Status = TaskStatus.Idle });

        TaskRowViewModel? removed = null;
        vm.DeleteFromList = row => { removed = row; return Task.CompletedTask; };
        var closed = false;
        vm.CloseDetail = () => closed = true;

        await vm.DeleteTaskCommand.ExecuteAsync(null);

        Assert.Equal("task-del-1", worker.DeletedTaskId);
        Assert.Equal("task-del-1", removed?.Id);
        Assert.True(closed);
    }

    [Fact]
    public async Task DeleteTask_WhenTaskHasChildren_SurfacesErrorAndKeepsDetailOpen()
    {
        const string fkMessage = "This task has child tasks. Discard the planning session or delete child tasks first.";
        var worker = new RecordingWorkerClient { Result = (false, fkMessage) };
        var vm = BuildVm(worker);
        vm.Bind(new TaskRowViewModel { Id = "task-del-2", Status = TaskStatus.WaitingForChildren });

        var deleteFromListCalled = false;
        vm.DeleteFromList = _ => { deleteFromListCalled = true; return Task.CompletedTask; };
        var closed = false;
        vm.CloseDetail = () => closed = true;
        string? reportedError = null;
        vm.ShowErrorAsync = msg => { reportedError = msg; return Task.CompletedTask; };

        await vm.DeleteTaskCommand.ExecuteAsync(null);

        Assert.Equal(fkMessage, reportedError);
        Assert.False(deleteFromListCalled);
        Assert.False(closed);
    }

    [Fact]
    public void DeleteTask_WhenWorkerOffline_CommandIsDisabled()
    {
        var worker = new RecordingWorkerClient(isConnected: false);
        var vm = BuildVm(worker);
        vm.Bind(new TaskRowViewModel { Id = "task-del-3", Status = TaskStatus.Idle });

        Assert.False(vm.DeleteTaskCommand.CanExecute(null));
    }

    [Fact]
    public void DeleteTask_WhenTaskHasInteractiveSession_CommandIsDisabled()
    {
        var worker = new RecordingWorkerClient();
        var vm = BuildVm(worker);
        var row = new TaskRowViewModel { Id = "task-del-5", Status = TaskStatus.Idle };
        vm.Bind(row);

        Assert.True(vm.DeleteTaskCommand.CanExecute(null));

        row.HasInteractiveSession = true;

        Assert.False(vm.DeleteTaskCommand.CanExecute(null));
    }

    [Fact]
    public async Task DeleteTask_WhenWorkerThrowsInvalidOperationException_SurfacesErrorAndKeepsDetailOpen()
    {
        var worker = new RecordingWorkerClient { ThrowOnDelete = new InvalidOperationException("Connection is not active.") };
        var vm = BuildVm(worker);
        vm.Bind(new TaskRowViewModel { Id = "task-del-4", Status = TaskStatus.Idle });

        var deleteFromListCalled = false;
        vm.DeleteFromList = _ => { deleteFromListCalled = true; return Task.CompletedTask; };
        var closed = false;
        vm.CloseDetail = () => closed = true;
        string? reportedError = null;
        vm.ShowErrorAsync = msg => { reportedError = msg; return Task.CompletedTask; };

        await vm.DeleteTaskCommand.ExecuteAsync(null);

        Assert.Equal("Connection is not active.", reportedError);
        Assert.False(deleteFromListCalled);
        Assert.False(closed);
    }
}
