-- productKey = "<Player.UserId>_<Number<PurchaseId>>"

local function processReceipt(receiptInfo: receiptInfo)
	local playerProductKey, purchased = `{receiptInfo.PlayerId}_{receiptInfo.PurchaseId}`, false
	local success, errorMessage

	success, errorMessage = pcall(function()
		purchased = purchaseHistoryStore:GetAsync(playerProductKey)
	end)

	assert(success, `Data store error: {errorMessage}`)

	if success and purchased then
		return Enum.ProductPurchaseDecision.PurchaseGranted
	end
	
	local success, isPurchaseRecorded = pcall(function()
		return purchaseHistoryStore:UpdateAsync(playerProductKey, function(alreadyPurchased): boolean?
			if alreadyPurchased then return true end

			local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
			if not player then return end

			local success, result = pcall(
				Functions.products[receiptInfo.ProductId], 
				receiptInfo, 
				player
			)

			assert((success and result), `Failed to process a product purchase for ProductId: {receiptInfo.ProductId} Player: {player} Error: {result}`)

			return true
		end)
	end)

	assert(success, 'Failed to process receipt due to data store error.')

	if isPurchaseRecorded then
		return Enum.ProductPurchaseDecision.PurchaseGranted
	end
	return Enum.ProductPurchaseDecision.NotProcessedYet
end

MarketplaceService.ProcessReceipt = processReceipt

return module
