One-wayness proof of Elgamal
You are confusing two different security notions. 

The proof you describe is regarding the Onewayness under chosen-plaintext attacks (OW-CPA). Basically, this notion covers the idea that it shouldn't be possible for an adversary to decrypt a given ciphertext (i.e., encryption is one-way), even if he can encrypt chosen plaintexts. As the proof shows, ElGamal is OW-CPA secure under the Computational Diffie-Hellman (CDH) assumption.

However, you are asking about indistinguishibility (i.e., guessing if an encryption is for one message or another). That's a different notion (and actually, a much more relevant one). It can be shown that ElGamal is IND-CPA secure under the Decisional Diffie-Hellman (DDH) assumption, which is weaker than CDH. Your understanding is correct: if an adversary can break OW-CPA, then it certainly can break IND-CPA. In security we are actually interested in the contrapositive: if a scheme is IND-CPA, then automatically is OW-CPA.



Regarding the OW-CPA proof of ElGamal, you have to know that in the OW security game, the adversary does not choose the underlying message, but the challenger. That means that the challenger doesn't even have to know the actual underlying message for the challenge ciphertext (that's why it can output a random $Z$ for the ciphertext). 

Now, if an adversary can break OW-CPA, it means that he is capable to decompose $Z$ into $m$ and $g^{ab}$, in order to output $m$. The challenger then uses the result from the adversary to compute $g^{ab}$ as $Z/m$. Note that each time the adversary outputs a correct $m$ (which happens with probability $\epsilon$), the challenger succeeds in computing $g^{ab}$, since for each random $Z$, there is always one $m$ such that $Z = m g^{ab}$.