using NATS.Server.Subscriptions;

namespace NATS.Server.LeafNodes;

/// <summary>
/// Helpers for building leaf-node subscription map keys.
/// Go reference: server/leafnode.go keyFromSub / keyFromSubWithOrigin.
/// </summary>
public static class LeafSubKey
{
    public const string KeyRoutedSub = "R";
    public const byte KeyRoutedSubByte = (byte)'R';
    public const string KeyRoutedLeafSub = "L";
    public const byte KeyRoutedLeafSubByte = (byte)'L';

    public static readonly TimeSpan SharedSysAccDelay = TimeSpan.FromMilliseconds(250);
    public static readonly TimeSpan ConnectProcessTimeout = TimeSpan.FromSeconds(2);

    public static string KeyFromSub(Subscription sub)
    {
        ArgumentNullException.ThrowIfNull(sub);
        return sub.Queue is { Length: > 0 }
            ? $"{sub.Subject} {sub.Queue}"
            : sub.Subject;
    }

    public static string KeyFromSubWithOrigin(Subscription sub, string? origin = null)
    {
        ArgumentNullException.ThrowIfNull(sub);
        var hasOrigin = !string.IsNullOrEmpty(origin);
        var prefix = hasOrigin ? KeyRoutedLeafSub : KeyRoutedSub;

        if (sub.Queue is { Length: > 0 })
        {
            if (hasOrigin)
                return $"{prefix} {sub.Subject} {sub.Queue} {origin}";

            return $"{prefix} {sub.Subject} {sub.Queue}";
        }

        if (hasOrigin)
            return $"{prefix} {sub.Subject} {origin}";

        return $"{prefix} {sub.Subject}";
    }
}
