Custom post type rewrite url structure with taxonomy and sub taxonomy

I’m building a cars post type, so I have ( brands/models ) as a custom taxonomy ( it’s only one taxonomy ) and all created by the CPT UI plugin.

Now I need the URL for the custom post type to be the following sitename/cars/parent-taxonomy/child-taxonomy/postname

so in real life example will be sitename/cars/opel/astra/xxxxx now I have rewrite the URL to be like this /cars/%brand_and_model% and I added the following code in functions.php

function wpa_show_permalinks( $post_link, $post ){
    if ( is_object( $post ) && $post->post_type == 'cars' ){
        $terms = wp_get_object_terms( $post->ID, 'brands_and_models' );
        if( $terms ){
            
            
            return str_replace( '%brands_and_models%' ,$terms(0)->slug , $post_link );
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );

but it’s not what I want it’s using only the primary term in the post type and not in the parent/child structure that I need to be.