How do I give dungeons sensible layouts that are still gameable?

When creating dungeons, I like to try to give them a history beyond “old place with traps and monsters and gold”, since I like everything to feel real and have a purpose. However, whenever I try to map out one of these, they either end up with planning that doesn’t make sense for what it is, or wouldn’t be fun to play through.

How do I create a dungeon layout that has/had purpose and would still be fun and challenging to explore?