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

namespace ClaudeDo.Ui.Tests.ViewModels;

public class TasksIslandSelectByIdTests : IDisposable
{
    private readonly string _dbPath;

    public TasksIslandSelectByIdTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_ui_selectbyid_{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 SeedAsync()
    {
        await using var db = NewContext();
        db.Lists.Add(new ListEntity
        {
            Id = "L1",
            Name = "Work",
            CreatedAt = DateTime.UtcNow,
        });
        db.Tasks.Add(new TaskEntity
        {
            Number = TestTaskNumbers.Next(),
            Id = "T1",
            ListId = "L1",
            Title = "My task",
            Status = TaskStatus.Idle,
            ParentTaskId = null,
            CreatedAt = DateTime.UtcNow,
            SortOrder = 0,
        });
        await db.SaveChangesAsync();
    }

    [Fact]
    public async Task SelectByIdAsync_ReturnsTrue_AndSetsSelectedTask()
    {
        await SeedAsync();
        var factory = new TestDbFactory(NewContext);
        var vm = new TasksIslandViewModel(factory, worker: null);

        vm.LoadForList(new ListNavItemViewModel { Id = "user:L1", Name = "Work", Kind = ListKind.User });
        var found = await vm.SelectByIdAsync("T1");

        Assert.True(found);
        Assert.Equal("T1", vm.SelectedTask?.Id);
    }

    [Fact]
    public async Task SelectByIdAsync_MissingId_ReturnsFalse_AndLeavesSelectedTaskNull()
    {
        await SeedAsync();
        var factory = new TestDbFactory(NewContext);
        var vm = new TasksIslandViewModel(factory, worker: null);

        vm.LoadForList(new ListNavItemViewModel { Id = "user:L1", Name = "Work", Kind = ListKind.User });
        var found = await vm.SelectByIdAsync("missing");

        Assert.False(found);
        Assert.Null(vm.SelectedTask);
    }
}
