local addonName, ApiVault = ...

ApiVault.EventTester = ApiVault.EventTester or {}
ApiVault.EventTester.active = {}
ApiVault.EventTester.frame = CreateFrame("Frame")

local MAX_ACTIVE_EVENTS = 12

local function isValidDocumentedEventName(eventName)
	return type(eventName) == "string" and string.match(eventName, "^[A-Z0-9_]+$") ~= nil
end

local function countActiveEvents(active)
	local count = 0
	for _ in pairs(active or {}) do
		count = count + 1
	end
	return count
end

ApiVault.EventTester.frame:SetScript("OnEvent", function(_, event, ...)
	local payload = { ... }
	local lines = { "Event: " .. tostring(event) }
	for index = 1, select("#", ...) do
		local value = payload[index]
		table.insert(lines, "[" .. index .. "] " .. ((ApiVault.ReturnSerializer and ApiVault.ReturnSerializer.Serialize and ApiVault.ReturnSerializer:Serialize(value)) or ApiVault:Serialize(value)))
	end
	local text = table.concat(lines, "\n")
	if ApiVault.UI and ApiVault.UI.AppendResult then
		ApiVault.UI:AppendResult(text)
	else
		ApiVault:Print(text)
	end
end)

function ApiVault.EventTester:IsListening(eventName)
	return self.active[eventName] == true
end

function ApiVault.EventTester:Toggle(eventName)
	if not eventName or eventName == "" then
		return false, "No event selected."
	end
	if not isValidDocumentedEventName(eventName) then
		return false, "Blocked: invalid event literal. ApiVault only registers documented uppercase event names."
	end
	if self.active[eventName] then
		self.frame:UnregisterEvent(eventName)
		self.active[eventName] = nil
		return true, "Stopped listening for " .. eventName
	end
	if countActiveEvents(self.active) >= MAX_ACTIVE_EVENTS then
		return false, "Blocked: active event listener cap reached. Stop another event listener first."
	end
	local ok, err = pcall(function()
		self.frame:RegisterEvent(eventName)
	end)
	if not ok then
		return false, err
	end
	self.active[eventName] = true
	return true, "Listening for " .. eventName
end
