namespace ZB.MOM.WW.MxGateway.Tests.ProjectStructure;

/// <summary>
/// Repo-hygiene guards over the source tree. A Windows-absolute default path that
/// resolves relative to the launch working directory silently materializes a SQLite credential
/// store inside the tree. This test fails if any such <c>*.db</c> file appears under <c>src/</c>.
/// </summary>
public sealed class GatewayTreeHygieneTests
{
    /// <summary>Verifies no SQLite database files are committed/materialized under the source tree (build output excluded).</summary>
    [Fact]
    public void SourceTree_ContainsNoSqliteDatabaseFiles()
    {
        DirectoryInfo sourceRoot = FindSourceRoot();

        string[] databaseFiles = Directory
            .EnumerateFiles(sourceRoot.FullName, "*.db", SearchOption.AllDirectories)
            .Where(path => !IsBuildOutput(path))
            .ToArray();

        Assert.True(
            databaseFiles.Length == 0,
            "Unexpected *.db file(s) found under the source tree (build output excluded): "
            + string.Join(", ", databaseFiles)
            + ". A SQLite DB in the tree usually means a Windows-absolute default path resolved "
            + "relative to the working directory; see SEC-01.");
    }

    // Build output (bin/obj) is regenerated by test/compile runs and is gitignored, so exclude it.
    private static bool IsBuildOutput(string path)
    {
        string normalized = path.Replace('\\', '/');
        return normalized.Contains("/bin/", StringComparison.Ordinal)
            || normalized.Contains("/obj/", StringComparison.Ordinal);
    }

    // The directory holding ZB.MOM.WW.MxGateway.slnx is the src/ root of the working tree.
    private static DirectoryInfo FindSourceRoot()
    {
        DirectoryInfo? current = new(AppContext.BaseDirectory);

        while (current is not null)
        {
            if (File.Exists(Path.Combine(current.FullName, "ZB.MOM.WW.MxGateway.slnx")))
            {
                return current;
            }

            current = current.Parent;
        }

        throw new DirectoryNotFoundException("Could not locate src/ZB.MOM.WW.MxGateway.slnx from the test output directory.");
    }
}
