<?php
/**
 * ProductCacheInvalidationHook class.
 *
 * Clears PowerWidget product cache when products are updated or deleted.
 *
 * @package Ilabs\Firevert\Modules\PowerWidget\Hooks\Admin
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PowerWidget\Hooks\Admin;

use Ilabs\Firevert\Core\Repository\Cache\CacheRepository;
use Ilabs\Firevert\Modules\PowerWidget\Services\Repository\PowerWidgetRepository;
use WP_Post;

/**
 * Handles cache invalidation on product update/delete.
 */
class ProductCacheInvalidationHook {

	/**
	 * Registers cache invalidation hooks.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'save_post_product', array( $this, 'invalidate_on_save' ), 20, 2 );
		add_action( 'deleted_post', array( $this, 'invalidate_on_delete' ), 20 );
	}

	/**
	 * Invalidates cache when product is saved.
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    WP_Post object.
	 *
	 * @return void
	 */
	public function invalidate_on_save( int $post_id, WP_Post $post ): void {
		if ( 'product' !== $post->post_type ) {
			return;
		}

		/**
		 * Get container DI.
		 *
		 * @var CacheRepository $cache
		 */
		$cache = firevert_container()->get( 'cache_repository' );
		$cache->flush_group( PowerWidgetRepository::POWER_WIDGET_PRODUCTS_CACHE_GROUP );
	}

	/**
	 * Invalidates cache when product is deleted.
	 *
	 * @param int $post_id Post ID.
	 *
	 * @return void
	 */
	public function invalidate_on_delete( int $post_id ): void {
		$post = get_post( $post_id );

		if ( $post && 'product' === $post->post_type ) {
			/**
			 * Get container DI.
			 *
			 * @var CacheRepository $cache
			 */
			$cache = firevert_container()->get( 'cache_repository' );
			$cache->flush_group( PowerWidgetRepository::POWER_WIDGET_PRODUCTS_CACHE_GROUP );
		}
	}
}
