Viagra was not initially being developed as an erection pill it was a heart medication (I think) but turned out to be better at causing erections so they ran with that.
Sildenafil (Viagra) was developed to treat hypertension and angina. It had little effect, but was found to assist with maintaining erections, so it was further developed for that purpose. Later it was discovered to be effective for pulmonary hypertension and is approved for that use, as well.