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

namespace ClaudeDo.Ui.Tests.ViewModels;

// UX-Audit #1: "Open findings folder" used to do nothing when the list's repo has no
// .claudedo/ folder yet — now it raises ErrorReported instead of a silent no-op.
public class ListsIslandErrorFeedbackTests : IDisposable
{
    private readonly string _dbPath;

    public ListsIslandErrorFeedbackTests()
    {
        _dbPath = Path.Combine(Path.GetTempPath(), $"claudedo_lists_error_feedback_test_{Guid.NewGuid():N}.db");
        using var ctx = NewContext();
        ctx.Database.EnsureCreated();

        var dir = AppContext.BaseDirectory;
        while (dir is not null && !Directory.Exists(Path.Combine(dir, "src", "ClaudeDo.Localization", "locales")))
            dir = Path.GetDirectoryName(dir);
        Loc.Current = new Localizer(
            LocaleStore.Load(Path.Combine(dir!, "src", "ClaudeDo.Localization", "locales")), "en");
    }

    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 OpenFindings_WhenClaudedoFolderMissing_RaisesErrorReported()
    {
        var vm = new ListsIslandViewModel(new TestDbFactory(NewContext));
        var workingDir = Path.Combine(Path.GetTempPath(), $"claudedo_findings_missing_{Guid.NewGuid():N}");
        Directory.CreateDirectory(workingDir);
        try
        {
            var row = new ListNavItemViewModel { Id = "L1", Kind = ListKind.User, WorkingDir = workingDir };

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

            vm.OpenFindingsCommand.Execute(row);

            Assert.NotNull(reportedError);
            Assert.NotEqual(string.Empty, reportedError);
        }
        finally
        {
            try { Directory.Delete(workingDir, recursive: true); } catch { }
        }
    }
}
