If mortality of seeds by fungus infection is more important than seed dispersal by mammals, then it makes sense to produce capsaicin. Since birds are likely better at dispersal than mammals (and don't have teeth) preventing mammals from eating chilli peppers might also be a beneficial side effect of the production of capsaicin, even if not the main reason for it.
Evolution just works on chance mutations and capsaicin is just what chilli peppers happened to start producing. Maybe if they happened to make penicillin instead they'd be better off, but they just do with what they have and that is capsaicin. They were just lucky that birds and humans tolerate capsaicin.