namespace RolemasterDb.ImportTool.Tests;

internal static class TestRepositoryPaths
{
    private const string RepositoryRootEnvironmentVariable = "ROLEMASTERDB_REPOSITORY_ROOT";

    public static string GetRepositoryRoot()
    {
        var configuredRoot = Environment.GetEnvironmentVariable(RepositoryRootEnvironmentVariable);
        if (!string.IsNullOrWhiteSpace(configuredRoot))
        {
            var fullPath = Path.GetFullPath(configuredRoot);
            if (File.Exists(Path.Combine(fullPath, "RolemasterDB.slnx")))
            {
                return fullPath;
            }
        }

        var probes = new[]
        {
            new DirectoryInfo(AppContext.BaseDirectory),
            new DirectoryInfo(Directory.GetCurrentDirectory())
        };

        foreach (var probe in probes)
        {
            for (var current = probe; current is not null; current = current.Parent)
            {
                if (File.Exists(Path.Combine(current.FullName, "RolemasterDB.slnx")))
                {
                    return current.FullName;
                }
            }
        }

        throw new InvalidOperationException(
            $"Could not find the repository root for integration tests. Set {RepositoryRootEnvironmentVariable} to the repository path.");
    }
}
