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 TasksIslandApproveReviewTests : IDisposable
{
    private readonly string _dbPath;

    public TasksIslandApproveReviewTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_approve_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 ThrowingWorkerClient : StubWorkerClient
    {
        public string ExceptionMessage { get; init; } = "blocked: target working tree has uncommitted changes";
        public override Task<MergeResultDto?> ApproveReviewAsync(string taskId, string targetBranch) =>
            throw new Exception(ExceptionMessage);
    }

    [Fact]
    public async Task ApproveReview_WhenWorkerThrows_RaisesErrorReported()
    {
        var worker = new ThrowingWorkerClient();
        var factory = new TestDbFactory(NewContext);
        var vm = new TasksIslandViewModel(factory, worker);

        string? reportedError = null;
        vm.ErrorReported += msg => reportedError = msg;

        var row = new TaskRowViewModel { Id = "task-err-2", Status = TaskStatus.WaitingForReview };
        await vm.ApproveReviewCommand.ExecuteAsync(row);

        Assert.NotNull(reportedError);
        Assert.Contains(worker.ExceptionMessage, reportedError);
    }

    private sealed class ThrowingCancelWorkerClient : StubWorkerClient
    {
        public string ExceptionMessage { get; init; } =
            "A merge is in progress for this task; wait for it to finish before cancelling.";
        public override Task CancelReviewAsync(string taskId) => throw new Exception(ExceptionMessage);
    }

    [Fact]
    public async Task CancelReview_WhenWorkerThrows_RaisesErrorReported()
    {
        var worker = new ThrowingCancelWorkerClient();
        var factory = new TestDbFactory(NewContext);
        var vm = new TasksIslandViewModel(factory, worker);

        string? reportedError = null;
        vm.ErrorReported += msg => reportedError = msg;

        var row = new TaskRowViewModel { Id = "task-cancel-err-2", Status = TaskStatus.WaitingForReview };
        await vm.CancelReviewCommand.ExecuteAsync(row);

        Assert.NotNull(reportedError);
        Assert.Contains(worker.ExceptionMessage, reportedError);
    }
}
