--[[
    Teleports all players to within the specified part
]]

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")

local PlayerManager = require(ServerStorage.Source.Managers.PlayerManager)

return function(spawnPart)
	for _, player in pairs(Players:GetPlayers()) do
		if player.Character and player.Character.PrimaryPart then
			local primaryPart = player.Character.PrimaryPart
			if primaryPart:CanSetNetworkOwnership() then
				primaryPart:SetNetworkOwner(nil)
			end

			local cFrame =
				spawnPart.CFrame *
				CFrame.new(
					math.random(-spawnPart.Size.X * 0.5 * 100, spawnPart.Size.X * 0.5 * 100) / 100,
					3,
					math.random(-spawnPart.Size.Z * 0.5 * 100, spawnPart.Size.Z * 0.5 * 100) / 100
				)

			primaryPart.CFrame = cFrame

			if primaryPart:CanSetNetworkOwnership() then
				primaryPart:SetNetworkOwner(player)
			end
		else
			local serverPlayerComponent = PlayerManager.getFromPlayer(player)

			if serverPlayerComponent and serverPlayerComponent.status.currentState == "game" then
				serverPlayerComponent.stateMachine:get():startSpectating()
			end
		end
	end
end
