Mac automatically restarts after shutdown

I used to work as an Apple technician and I'v had several Macs that describe your issue, but they were only laptops. The issue with them was liquid damaged. Now you thinking how the h'll can an iMac get liquid damaged, but I can tell you, I'v actually seen it myself. So it's possible but maybe not in your case.

I recommend to let an Apple technician look at it. Water damage causes a fault in the circuitry, but the same fault can happen from other causes or just rare breakage.