namespace NATS.Server.LeafNodes;

public static class LeafLoopDetector
{
    private const string LeafLoopPrefix = "$LDS.";

    public static bool HasLoopMarker(string subject)
        => subject.StartsWith(LeafLoopPrefix, StringComparison.Ordinal);

    public static string Mark(string subject, string serverId)
        => $"{LeafLoopPrefix}{serverId}.{subject}";

    public static bool IsLooped(string subject, string localServerId)
        => subject.StartsWith($"{LeafLoopPrefix}{localServerId}.", StringComparison.Ordinal);

    public static bool TryUnmark(string subject, out string unmarked)
    {
        unmarked = subject;
        if (!HasLoopMarker(subject))
            return false;

        var current = subject;
        while (HasLoopMarker(current))
        {
            var serverSeparator = current.IndexOf('.', LeafLoopPrefix.Length);
            if (serverSeparator < 0 || serverSeparator == current.Length - 1)
                return false;

            current = current[(serverSeparator + 1)..];
        }

        unmarked = current;
        return true;
    }
}
