You're not looking at this from the Afghan perspective. From the American and Russian perspective, yes, occupying Afghanistan is a painful deathtrap. But for the Afghans their occupation is...also a painful deathtrap. Eventually winning (or even sort of winning) a war of low-tech attrition involves sacrificing a lot of lives, losing political control, and having foreign soldiers soldiers patrol your territory imposing their own laws. Afghanistan has to go through all this because they don't have a credible way to deter an invasion. That's why they keep getting invaded!
Obviously this didn't work for Afghanistan, but their example can help it work for others.
Edit: if you become part of a larger war then it can also be advantageous to make the occupation painful for the enemy when it happens. The more you hurt them, the easier and faster your allies will win. Consider Norway in the Second World War: they had no hope of overthrowing the German occupation themselves, but the resistance still contributed significantly to its eventual end.
> The goal is not to get invaded in the first place
with this one
> Afghanistan succeeded in getting the Soviets out in the end.
Afghanistan would beg to differ...
> Of course, a 10m country will never have a really credible defense against nuclear super power Russia by itself.
Unless the goal of fighting a war is to wipe the opposing side off the face of the earth, no, it's a credible defense. You bleed the enemy until they lose the will to fight.