Mechanistic studies of magnesium electrodeposition and oxygen reduction for energy storage applications