<?php
/**
 * WooCommerce product synchronization.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChangesWooCommerce\CoreCompat\WooCommerce;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- scheduled_changes_ is the product prefix.

/**
 * Runs supported WooCommerce sync and cache invalidation after writes.
 */
final class ProductSynchronizer {
	public function synchronize( \WC_Product $product ): void {
		$product_id = $product->get_id();
		$parent_id  = $product->get_parent_id();

		if ( $product instanceof \WC_Product_Variation && $parent_id > 0 ) {
			\WC_Product_Variable::sync( $parent_id );
			wc_delete_product_transients( $parent_id );
			clean_post_cache( $parent_id );
		} elseif ( $product instanceof \WC_Product_Variable ) {
			\WC_Product_Variable::sync( $product );
		}

		wc_delete_product_transients( $product_id );
		clean_post_cache( $product_id );

		/**
		 * Fires after WooCommerce product indexes and caches are synchronized.
		 *
		 * @param int $product_id Product or variation ID.
		 * @param int $parent_id Parent product ID when applicable.
		 */
		do_action( 'scheduled_changes_after_product_sync', $product_id, $parent_id );
	}
}
