How to rewrite product permalinks in Woocommerce to use category slugs

Ok, so the second code is:

function custom_rewrite_basic() {

    $prodCatArgs = ['taxonomy' => 'product_cat'];
    $wooCats = get_categories($prodCatArgs);
    $catSlugs = [];
    foreach($wooCats as $wooCat) {
        $catSlugs[] = $wooCat->slug;
    }
    add_rewrite_rule(
        '^('.implode('|', $catSlugs).')/([^/]*)/?',
        'index.php?post_type=product&category=$matches[1]&product=$matches[2]',
        'top'
    );
    flush_rewrite_rules();
}
add_action('init', 'custom_rewrite_basic');