Surgery is both a mass noun and a count noun. Note the Cambridge dictionary uses U for uncountable noun (mass noun) and C for count noun.
In brief, it is a mass noun when referring to
the treatment of injuries or diseases by cutting open the body and removing or repairing the damaged part,
It is a count noun, when it refers to
or an operation of this type.
See operation. And while operation is used in both American English (AmE) and British English (BrE), It seems that this particular count-noun use of 'surgery' to mean 'an operation' is used mainly in AmE.
The following questions regard 'surgery' as a mass (uncountable) noun:
Have you ever had surgery?
Have you ever had brain, knee, open-heart, elbow, lung, kidney, etc surgery?
Have you ever had surgery on your knee, leg, elbow, etc before?
The following questions refer to 'surgery' as a count noun. It is asking about countable instances of surgery or surgeries as operations. Again the dictionaries I have checked indicate this is mainly an AmE usage. To me, it is also important to notice that these questions use the word 'surgery' as a plural count noun:
Have you had any (other) surgeries (= operations)?
How many surgeries (= operations) have you had (on your knee, leg, elbow, heart, brain, etc)?
The American (?) usage as both mass and count noun allows both the following sentences, which convey the same information:
As a mass noun
John is recovering from surgery. He won't return to work for a week.
As a count noun
John is recovering from his surgery. He won't return to work for a week.
Note that even though 'surgery' can be used as a singular count noun, we would not normally use 'a surgery' in the last sentence. And, in general, although Americans do say 'a surgery', it sounds weird to me. Therefore, I think the answer to to your question
Can't we ask
Have you ever had a surgery?
may depend on which speaker of American English that you ask. I personally would probably not say it. I might say 'a surgical procedure' or, of course, 'an operation'.
Whereas, I don't think any American in their right mind would ask:
Have you ever had a brain (heart, lung, kidney, elbow, etc) surgery before?
Although, usage may vary, not only among speakers, but regarding which part of the body is being operated on. I can see someone saying 'I have a knee surgery tomorrow', but not 'I have a brain surgery tomorrow'. Maybe because we have two knees but only one brain? I dunno.
You can do an Internet search for 'had a surgery' and 'had surgery' to get a good idea of this difference in usage (mass versus count).
Note that 'surgery' also has some other, related meanings, which vary in usage between American English and British English. For instance, in BrE, 'a surgery' is where you go to see a doctor; in AmE we say 'office' for this. You can read about this and a couple other definitions in most dictionaries, including this one.