using ClaudeDo.Ui.Services;

namespace ClaudeDo.Ui.Tests.Services;

public class InstallerLocatorTests : IDisposable
{
    private readonly string _root;

    public InstallerLocatorTests()
    {
        _root = Path.Combine(Path.GetTempPath(), "ClaudeDo.Ui.Tests-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(_root);
    }

    public void Dispose() { try { Directory.Delete(_root, true); } catch { } }

    [Fact]
    public void Find_WalkUpFromAppDir_ToInstallJsonSibling()
    {
        var installDir = Path.Combine(_root, "ClaudeDo");
        var appDir = Path.Combine(installDir, "app");
        var uninstallerDir = Path.Combine(installDir, "uninstaller");
        Directory.CreateDirectory(appDir);
        Directory.CreateDirectory(uninstallerDir);

        File.WriteAllText(Path.Combine(installDir, "install.json"), "{}");
        var installerPath = Path.Combine(uninstallerDir, "ClaudeDo.Installer.exe");
        File.WriteAllText(installerPath, "x");

        var locator = new InstallerLocator();
        var found = locator.FindByWalkingUp(appDir);

        Assert.Equal(installerPath, found);
    }

    [Fact]
    public void Find_ReturnsNullWhenNoInstallJson()
    {
        var appDir = Path.Combine(_root, "somewhere", "app");
        Directory.CreateDirectory(appDir);

        var locator = new InstallerLocator();
        Assert.Null(locator.FindByWalkingUp(appDir));
    }

    [Fact]
    public void Find_ReturnsNullWhenInstallerMissingFromUninstallerDir()
    {
        var installDir = Path.Combine(_root, "ClaudeDo");
        var appDir = Path.Combine(installDir, "app");
        Directory.CreateDirectory(appDir);
        Directory.CreateDirectory(Path.Combine(installDir, "uninstaller"));
        File.WriteAllText(Path.Combine(installDir, "install.json"), "{}");

        var locator = new InstallerLocator();
        Assert.Null(locator.FindByWalkingUp(appDir));
    }
}
