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

namespace ClaudeDo.Ui.Tests.ViewModels;

public class TasksIslandAddAndSelectTests : IDisposable
{
    private readonly string _dbPath;

    public TasksIslandAddAndSelectTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_ui_addselect_{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 async Task SeedListAsync()
    {
        await using var db = NewContext();
        db.Lists.Add(new ListEntity { Id = "L1", Name = "Work", CreatedAt = DateTime.UtcNow });
        await db.SaveChangesAsync();
    }

    [Fact]
    public async Task AddAsync_SelectsNewTask()
    {
        await SeedListAsync();
        var vm = new TasksIslandViewModel(new TestDbFactory(NewContext), worker: null);
        vm.LoadForList(new ListNavItemViewModel { Id = "user:L1", Name = "Work", Kind = ListKind.User });
        await vm.LoadTask!;

        vm.NewTaskTitle = "My new task";
        await vm.AddCommand.ExecuteAsync(null);

        Assert.NotNull(vm.SelectedTask);
        Assert.Equal("My new task", vm.SelectedTask!.Title);
    }

    [Fact]
    public async Task AddAsync_EmptyTitle_DoesNotChangeSelection()
    {
        await SeedListAsync();
        var vm = new TasksIslandViewModel(new TestDbFactory(NewContext), worker: null);
        vm.LoadForList(new ListNavItemViewModel { Id = "user:L1", Name = "Work", Kind = ListKind.User });
        await vm.LoadTask!;

        vm.NewTaskTitle = "";
        await vm.AddCommand.ExecuteAsync(null);

        Assert.Null(vm.SelectedTask);
    }
}
