do a visual inspection of the brake light switch with someone activating the pedal, the switch arm can be bent or otherwise out of position, might also use an ohmmeter to check switch function to detect poor internal contact .... problems with rear light function can be caused by poor ground connections, make sure the light mounts are clean and tight, and maybe add a dedicated ground from the light to the frame
Bill