local EnsureApiRegistry = rawget(_G, "LIDCOUNCIL_EnsureApiRegistry")
local API, INTERNAL_API
if type(EnsureApiRegistry) == "function" then
  API, INTERNAL_API = EnsureApiRegistry()
else
  API = rawget(_G, "LIDCOUNCIL_API")
  if type(API) ~= "table" then
    API = {}
    _G.LIDCOUNCIL_API = API
  end
  if type(API.__internal) ~= "table" then
    API.__internal = {}
  end
  INTERNAL_API = API.__internal
end

INTERNAL_API.LIDCOUNCIL_CreateOutboundFlushTimerStateHelpers_Impl = function()
  local function ClearOutboundCommFlushSchedule(state)
    state = type(state) == "table" and state or {}
    state.token = math.max(0, tonumber(state.token) or 0) + 1
    state.nextAt = 0
    return state.token
  end

  local function BeginOutboundCommFlushSchedule(state, dueAt)
    state = type(state) == "table" and state or {}
    state.token = math.max(0, tonumber(state.token) or 0) + 1
    state.nextAt = math.max(0, tonumber(dueAt) or 0)
    return state.token
  end

  local function ConsumeOutboundCommFlushSchedule(state, token)
    state = type(state) == "table" and state or {}
    if math.max(0, tonumber(token) or 0) ~= math.max(0, tonumber(state.token) or 0) then
      return false
    end
    state.nextAt = 0
    return true
  end

  local function GetOutboundCommFlushNextAt(state)
    return math.max(0, tonumber(type(state) == "table" and state.nextAt or 0) or 0)
  end

  return {
    ClearOutboundCommFlushSchedule = ClearOutboundCommFlushSchedule,
    BeginOutboundCommFlushSchedule = BeginOutboundCommFlushSchedule,
    ConsumeOutboundCommFlushSchedule = ConsumeOutboundCommFlushSchedule,
    GetOutboundCommFlushNextAt = GetOutboundCommFlushNextAt,
  }
end
