// Copyright 2012-2026 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");

namespace ZB.MOM.NatsNet.Server;

internal static class RouteHandler
{
    internal static int ComputeRoutePoolIdx(int poolSize, string accountName) =>
        NatsServer.ComputeRoutePoolIdx(poolSize, accountName);

    internal static string GetAccNameFromRoutedSubKey(Internal.Subscription sub, string key, bool keyHasSubType)
    {
        _ = sub;
        var fields = key.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (fields.Length == 0)
            return string.Empty;

        var accountIndex = keyHasSubType ? 1 : 0;
        if (accountIndex >= fields.Length)
            return string.Empty;

        return fields[accountIndex];
    }

    internal static bool RouteShouldDelayInfo(string accName, ServerOptions opts) =>
        string.IsNullOrEmpty(accName) && opts.Cluster.PoolSize >= 1;

    internal static bool HasSolicitedRoute(IReadOnlyList<ClientConnection> routes, string accName)
    {
        foreach (var route in routes)
        {
            if (route.Route?.DidSolicit != true)
                continue;

            var routeAcc = route.Route?.AccName is { Length: > 0 } an
                ? System.Text.Encoding.ASCII.GetString(an)
                : string.Empty;
            if (routeAcc == accName)
                return true;
        }
        return false;
    }

    internal static void UpgradeRouteToSolicited(ClientConnection route)
    {
        if (route.Route is null)
            return;
        route.Route.DidSolicit = true;
        route.Route.Retry = true;
    }

    internal static bool HandleDuplicateRoute(ClientConnection existing, ClientConnection incoming)
    {
        if (existing.IsSolicitedRoute() && !incoming.IsSolicitedRoute())
            return false;
        if (!existing.IsSolicitedRoute() && incoming.IsSolicitedRoute())
            return true;
        return incoming.Cid > existing.Cid;
    }
}
