namespace ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests.Cluster;

/// <summary>
/// One-shot probe for whether the dev cluster (and its MSSQL config store) is
/// reachable through the CLI. State-changing E2E tests gate their setup on this so
/// a downed cluster surfaces as a Skipped fact (via <c>Skip.IfNot</c>) rather than
/// an opaque failure. The result is cached for the process; <see cref="SkippedCount"/>
/// is bumped each time a test would skip and is logged at suite teardown (Task 3).
/// </summary>
public static class ClusterAvailability
{
    /// <summary>Reason surfaced on skipped facts when the cluster is unavailable.</summary>
    public const string SkipReason =
        "Cluster/MSSQL unavailable — start the docker cluster (bash docker/deploy.sh) to run E2E.";

    private static bool? _cached;

    /// <summary>
    /// Number of times a test would have skipped because the cluster is
    /// unavailable. Incremented on every <see cref="IsAvailableAsync"/> call that
    /// returns <see langword="false"/>; logged at suite teardown (Task 3).
    /// </summary>
    public static int SkippedCount;

    /// <summary>
    /// Returns whether the cluster is reachable, probing once (a <c>site list</c>
    /// round-trip through the CLI) and caching the result for the process.
    /// </summary>
    public static async Task<bool> IsAvailableAsync()
    {
        if (_cached is { } cached)
        {
            if (!cached)
            {
                System.Threading.Interlocked.Increment(ref SkippedCount);
            }

            return cached;
        }

        try
        {
            using var _ = await CliRunner.RunJsonAsync("site", "list");
            _cached = true;
        }
        catch
        {
            _cached = false;
            System.Threading.Interlocked.Increment(ref SkippedCount);
        }

        return _cached.Value;
    }
}
