It appears that the issue lies with the in_array function that is checking if the current post type matches the post types specified in the template header information. The problem seems to be that the REST API is validating the parameters, including the template parameter, before passing it to the WordPress API to update the post.
It’s possible that the REST API is only allowing certain values for the template parameter and the values generated by the in_array function are not accepted. You can try to debug this by logging the values of $post_type and $post_types before and after the in_array function, as well as the $custom_templates array.
Another possible solution is to modify the REST API check_template method to accept the values generated by the in_array function. This would involve creating a custom REST API controller for the posts endpoint and including the check for the custom templates in the check_template method.
Lastly, you could also try using the WP_Query class instead of the REST API to retrieve and update the templates, as it is not as strict in terms of parameter validation.