using ClaudeDo.Data;

namespace ClaudeDo.Data.Tests;

public class LegacyAppDataRootMigrationTests : IDisposable
{
    private readonly string _home = Path.Combine(Path.GetTempPath(), $"claudedo_home_{Guid.NewGuid():N}");

    public void Dispose()
    {
        try { Directory.Delete(_home, true); } catch { /* best effort */ }
    }

    [Fact]
    public void MovesLegacyRootAndRewritesConfigPaths()
    {
        var legacy = Path.Combine(_home, ".todo-app");
        Directory.CreateDirectory(Path.Combine(legacy, "logs"));
        File.WriteAllText(Path.Combine(legacy, "todo.db"), "db");
        File.WriteAllText(Path.Combine(legacy, "worker.config.json"),
            """{"db_path":"~/.todo-app/todo.db","log_root":"~/.todo-app/logs"}""");

        Paths.MigrateLegacyAppDataRoot(_home);

        var root = Path.Combine(_home, ".claudeDo");
        Assert.False(Directory.Exists(legacy));
        Assert.Equal("db", File.ReadAllText(Path.Combine(root, "todo.db")));
        Assert.True(Directory.Exists(Path.Combine(root, "logs")));
        Assert.Equal(
            """{"db_path":"~/.claudeDo/todo.db","log_root":"~/.claudeDo/logs"}""",
            File.ReadAllText(Path.Combine(root, "worker.config.json")));
    }

    [Fact]
    public void LeavesLegacyRootAloneOnceTargetExists()
    {
        var legacy = Path.Combine(_home, ".todo-app");
        var root = Path.Combine(_home, ".claudeDo");
        Directory.CreateDirectory(legacy);
        Directory.CreateDirectory(root);
        File.WriteAllText(Path.Combine(root, "todo.db"), "new");

        Paths.MigrateLegacyAppDataRoot(_home);

        Assert.True(Directory.Exists(legacy));
        Assert.Equal("new", File.ReadAllText(Path.Combine(root, "todo.db")));
    }
}
