From what I've read about some medicines it's something like "We originally used it for this but it turns out it stops this too! (we're not entirely sure why)"
Viagra for example, was originally studied for high blood pressure.
I've also seen a tv program where they visited a pharmacy company's lab that's literally machines mixing random drugs in order to find their next product. The place was the size of a walmart.