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_CreateOutboundTimerAdapterHelpers_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}
  local GetTimerAfter = type(deps.GetTimerAfter) == "function" and deps.GetTimerAfter or function()
    return nil
  end
  local TrimText = type(deps.TrimText) == "function" and deps.TrimText or function(value)
    return tostring(value or "")
  end

  local function ScheduleTimer(delaySeconds, callback)
    if type(callback) ~= "function" then
      return false, "callback_invalid"
    end
    local timerAfter = GetTimerAfter()
    if type(timerAfter) ~= "function" then
      return false, "unavailable"
    end
    local ok, scheduled, scheduleReason = pcall(
      timerAfter,
      math.max(0, tonumber(delaySeconds) or 0),
      callback
    )
    if not ok then
      return false, "error"
    end
    if scheduled == false then
      local resolvedReason = TrimText(scheduleReason)
      return false, resolvedReason ~= "" and resolvedReason or "unavailable"
    end
    local resolvedReason = TrimText(scheduleReason)
    return true, resolvedReason ~= "" and resolvedReason or "scheduled"
  end

  local function BuildSessionTimerFallbackStatus(sessionTotal, runtimeTotal, lastAt, lastReason)
    local resolvedSessionTotal = math.max(0, tonumber(sessionTotal) or 0)
    return {
      sessionTotal = resolvedSessionTotal,
      runtimeTotal = math.max(0, tonumber(runtimeTotal) or 0),
      lastAt = resolvedSessionTotal > 0 and math.max(0, tonumber(lastAt) or 0) or 0,
      lastReason = resolvedSessionTotal > 0 and TrimText(lastReason) or "",
    }
  end

  return {
    ScheduleTimer = ScheduleTimer,
    ScheduleOutboundFlushTimer = ScheduleTimer,
    BuildSessionTimerFallbackStatus = BuildSessionTimerFallbackStatus,
  }
end
