Trying to figure out the absolute chain-of-command is a lot like trying to figure out a meaningful and accurate formula for "stardates" that fit all its citations ... you can't.
Generally, Scotty was the goto third in command but not always. Sometimes it was given to Sulu. Sometimes a rarely seen Lt. DeSalle. It was even worse in The Next Generation.
Of course in TOS it was predicated on how familiar the writers were with Trek, availability, story, etc. ... After Mr. Scott it boiled down to whoever was handy with no real regard to anything other than it couldn't be a woman.
TNG went overboard where anyone could find themselves in command - Troi, Crusher, the gimpy half-blind janitor on deck 23, literally anybody ...