A quick workaround for windows to switch back to the correct monitor when disconnecting the second monitor and connecting it back.
If you minimize all windows (Option+Command+H+M) before connecting back the second monitor, windows will be in the same monitor they were previously when you click in their dock's icons.