Is there any way for the only legal move is to checkmate the opponent


This chess stackexchange post has a couple examples of it, one such position I've included in this comment.

There is and Gotham Chess made a video on a game where a player made a blunder where he essentially forced checkmate on himself.
https://youtu.be/Sew_n0SDjT0?si=74AkQzwrK5eBrnMt


The only way to lose to the Worstfish bot is by doing this. The closest I've seen in a game I played is when my opponent had an M2 and then hung M1 on themselves five moves later.

There is this one that has always raised controversy in USCF vs FIDE rules.
I don't know if USCF has tweaked this rule or not, but FIDE has always been that if time runs out for Black in the following, it would be a draw as there is no sequence of legal moves for White to win. USCF, at least in the past, this would be a win for White if Black's flag fell due to sufficient material.
The issue is what the OPquestioned - Black's only legal moves is to checkmate the White King.
Only legal moves is 1...Rg7#.