--[[*
 * This API should be called `delete` but we'd have to make sure to always
 * transform these to strings for IE support. When this transform is fully
 * supported we can rename it.
 ]]


local Shared = script.Parent
local Packages = Shared.Parent
local LuauPolyfill = require(Packages.LuauPolyfill)
local Error = LuauPolyfill.Error
local inspect = LuauPolyfill.util.inspect
local getComponentName = require(script.Parent.getComponentName)

local exports = {}

local function isValidFiber(fiber): boolean
	return fiber.tag ~= nil
		and fiber.subtreeFlags ~= nil
		and fiber.lanes ~= nil
		and fiber.childLanes ~= nil
end

exports.remove = function(key)
	key._reactInternals = nil
end

exports.get = function(key)
	local value = key._reactInternals

	-- ROBLOX deviation: we have a crash in production this will help catch
	-- ROBLOX TODO: wrap this in __DEV__
	if not isValidFiber(value) then
		error(
			Error.new(
				"invalid fiber in "
					.. (getComponentName(key) or "UNNAMED Component")
					.. " during get from ReactInstanceMap! "
					.. inspect(value)
			)
		)
	elseif value.alternate ~= nil and not isValidFiber(value.alternate) then
		error(
			Error.new(
				"invalid alternate fiber ("
					.. (getComponentName(key) or "UNNAMED alternate")
					.. ") in "
					.. (getComponentName(key) or "UNNAMED Component")
					.. " during get from ReactInstanceMap! "
					.. inspect(value.alternate)
			)
		)
	end

	return value
end

exports.has = function(key)
	return key._reactInternals ~= nil
end

exports.set = function(key, value)
	-- ROBLOX deviation: we have a crash in production this will help catch
	-- ROBLOX TODO: wrap this in __DEV__
	local parent = value
	local message
	while parent ~= nil do
		if not isValidFiber(parent) then
			message = "invalid fiber in "
				.. (getComponentName(key) or "UNNAMED Component")
				.. " being set in ReactInstanceMap! "
				.. inspect(parent)
				.. "\n"

			if value ~= parent then
				message ..= " (from original fiber " .. (getComponentName(key) or "UNNAMED Component") .. ")"
			end
			error(Error.new(message))
		elseif
			(parent :: any).alternate ~= nil
			and not isValidFiber((parent :: any).alternate)
		then
			message = "invalid alternate fiber ("
				.. (getComponentName(key) or "UNNAMED alternate")
				.. ") in "
				.. (getComponentName(key) or "UNNAMED Component")
				.. " being set in ReactInstanceMap! "
				.. inspect((parent :: any).alternate)
				.. "\n"

			if value ~= parent then
				message ..= " (from original fiber " .. (getComponentName(key) or "UNNAMED Component") .. ")"
			end
			error(Error.new(message))
		end
		parent = (parent :: any).return_
	end

	(key :: any)._reactInternals = value
end

return exports
