Thus, the obligation is simply to select, from those who are actually available, the one who is most pleasing to Allah. In most situations a faultless person cannot be found, so one pursues the better of the two good options and wards off the worse of the two evils. For this reason ʿUmar ibn al-Khaṭṭāb used to say, “I complain to You of the audacity of the wicked and the helplessness of the trustworthy.”
The Prophet ﷺ and his Companions rejoiced when the Byzantines—the Christians—defeated the Magians, even though both sides were disbelievers, because one of the two was closer to Islam. Concerning that event Allah revealed Surah al-Rum at the time when the Romans and the Persians fought one another; the story is well known.
In the same way, Joseph served as a deputy to the Pharaoh of Egypt while Pharaoh and his people were polytheists. He carried out as much justice and goodness as he could, and he called them to faith to the extent that was possible.