$out_of_stock_staus = 'outofstock';
// 1. Updating the stock quantity
update_post_meta($product_id, '_stock', 0);
// 2. Updating the stock quantity
update_post_meta( $product_id, '_stock_status', wc_clean( $out_of_stock_staus ) );
// 3. Updating post term relationship
wp_set_post_terms( $product_id, 'outofstock', 'product_visibility', true );
// And finally (optionally if needed)
wc_delete_product_transients( $product_id ); // Clear/refresh the variation cache