-- Local Functions

local function awardBadge(player, badgeId)
	-- Fetch badge information
	local success, badgeInfo = pcall(function()
		return BadgeService:GetBadgeInfoAsync(badgeId)
	end)
	if success then
		-- Confirm that badge can be awarded
		if badgeInfo.IsEnabled then
			-- Award badge
			local awarded, errorMessage = pcall(function()
				BadgeService:AwardBadge(player.UserId, badgeId)
				return true
			end)
			if not awarded then
				warn("Error while awarding badge:", errorMessage)
				return false
			end
		end
	else
		warn("Error while fetching badge info!")
		return false
	end
end

local function handleCodeRedemption(player, code)
	-- Check if code is valid
	local foundIndex = false
	for codeIndex, badgeId in ipairs (GameSettings.codes) do
		if codeIndex == code then
			foundIndex = codeIndex
		end
	end
	
	if not foundIndex then
		RedeemCode:FireClient(player, "Invalid code!")
		return 
	end

	-- Player has redeemed code, can't redeem again
	if DataStore:HasRedeemedCode(player, code) then
		RedeemCode:FireClient(player, "Code already redeemed!")
		return 
	end
	
	local redeemed = DataStore:RedeemCode(player, GameSettings.codes[foundIndex])
	if redeemed then
		-- Give prize based on code
		if awardBadge(player, GameSettings.codes[foundIndex]) then
			-- Tell client that code has been redeemed
			RedeemCode:FireClient(player, "Successfully redeemed!")
		end
	end
	
	-- Tell client that code has been redeemed
	RedeemCode:FireClient(player, "Error redeeming code!")
end

