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

namespace ClaudeDo.Ui.Tests.ViewModels;

public class TasksIslandOpenQuickClaudeSessionTests : IDisposable
{
    private readonly string _dbPath;

    public TasksIslandOpenQuickClaudeSessionTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_quickclaude_{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 TasksIslandViewModel BuildViewModel() => new(new TestDbFactory(NewContext), worker: null);

    private static ListNavItemViewModel UserList(string? workingDir) =>
        new() { Id = "user:l1", Kind = ListKind.User, Name = "L1", WorkingDir = workingDir };

    [Fact]
    public void NoWorkingDirConfigured_ReportsError_DoesNotRaiseRequested()
    {
        var vm = BuildViewModel();
        vm.LoadForList(UserList(workingDir: null));
        string? error = null;
        var requested = false;
        vm.ErrorReported += msg => error = msg;
        vm.OpenQuickClaudeSessionRequested += _ => requested = true;

        vm.OpenQuickClaudeSessionCommand.Execute(null);

        Assert.NotNull(error);
        Assert.False(requested);
    }

    [Fact]
    public void WorkingDirMissingOnDisk_ReportsError_DoesNotRaiseRequested()
    {
        var missingDir = Path.Combine(Path.GetTempPath(), $"claudedo_missing_{Guid.NewGuid():N}");
        var vm = BuildViewModel();
        vm.LoadForList(UserList(workingDir: missingDir));
        string? error = null;
        var requested = false;
        vm.ErrorReported += msg => error = msg;
        vm.OpenQuickClaudeSessionRequested += _ => requested = true;

        vm.OpenQuickClaudeSessionCommand.Execute(null);

        Assert.NotNull(error);
        Assert.Contains(missingDir, error);
        Assert.False(requested);
    }

    [Fact]
    public void WorkingDirExists_RaisesRequested_WithDir_NoError()
    {
        var dir = Path.GetTempPath();
        var vm = BuildViewModel();
        vm.LoadForList(UserList(workingDir: dir));
        string? error = null;
        string? requestedDir = null;
        vm.ErrorReported += msg => error = msg;
        vm.OpenQuickClaudeSessionRequested += d => requestedDir = d;

        vm.OpenQuickClaudeSessionCommand.Execute(null);

        Assert.Null(error);
        Assert.Equal(dir, requestedDir);
    }
}
