Without entering into other details of the text, I would like to draw attention to one more point: the building of the rampart against Gog and Magog (also known as Yajuj and Majuj).
This motif is a repetition of Khidr’s last deed in the previous episode, the rebuilding of the town wall.
But this time the wall is to be a strong defence against Gog and Magog.
The passage may possibly refer to Revelation 20:ηί. (AV):
And when the thousand years are expired, Satan shall be loosed out of his prison, and shall go out to deceive the nations which are in the four quarters of the earth, Gog and Magog, to gather them together for battle: the number of whom is as the sand of the sea.
And they went up on the breadth of the earth, and compassed the camp of the saints about, and the beloved city.
Here Dhulqarnein takes over the role of Khidr and builds an unscalable rampart for the people living “between Two Mountains.”
This is obviously the same place in the middle which is to be protected against Gog and Magog, the featureless, hostile masses.
Psychologically, it is again a question of the self, enthroned in the place of the middle, and referred to in Revelation as the beloved city (Jerusalem, the centre of the earth).
The self is the hero, threatened already at birth by envious collective forces; the jewel that is coveted by all and arouses jealous strife; and finally the god who is dismembered by the old, evil power of darkness.
In its psychological meaning, individuation is an opus contra naturam, which creates a horror vacui in the collective layer and is only too likely to collapse under the impact of the collective forces of the psyche.
The mystery legend of the two helpful friends promises protection to him who has found the jewel on his quest.
But there will come a time when, in accordance with Allah’s providence, even the iron rampart will fall to pieces, namely, on the day when the world comes to an end, or psychologically speaking, when individual consciousness is extinguished in the waters of darkness, that is to say when a subjective end of the world is experienced.
By this is meant the moment when consciousness sinks back into the darkness from which it originally emerged, like Khidr’s island: the moment of death. ~Carl Jung, CW 9i, Pages 146-147