using ClaudeDo.Data;
using ClaudeDo.Ui.ViewModels.Islands;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Ui.Tests.ViewModels;

public class TasksIslandOpenConPtySessionTests : IDisposable
{
    private readonly string _dbPath;

    public TasksIslandOpenConPtySessionTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_conpty_cmd_{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);
    }


    [Fact]
    public void OpenConPtySessionCommand_RaisesOpenConPtySessionRequested_WithTaskId()
    {
        var vm = new TasksIslandViewModel(new TestDbFactory(NewContext), worker: null);
        string? requestedId = null;
        vm.OpenConPtySessionRequested += id => requestedId = id;

        vm.OpenConPtySessionCommand.Execute(new TaskRowViewModel { Id = "t1" });

        Assert.Equal("t1", requestedId);
    }

    [Fact]
    public void OpenConPtySessionCommand_NullRow_DoesNotRaiseEvent()
    {
        var vm = new TasksIslandViewModel(new TestDbFactory(NewContext), worker: null);
        var raised = false;
        vm.OpenConPtySessionRequested += _ => raised = true;

        vm.OpenConPtySessionCommand.Execute(null);

        Assert.False(raised);
    }
}
