The castle served as a fortification for the Romans, Visigoths and the Moors, who turned it into a royal palace before it was eventually taken by Portugal's first king, Afonso Henriques.