<?php
/**
 * WooCommerce product hooks → sync queue.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Hooks;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Queue\SyncQueue;

class ProductHooks {

	private SyncQueue $queue;

	/** Props that trigger a Sheets push when changed. */
	private const WATCHED_PROPS = array(
		'name',
		'sku',
		'status',
		'regular_price',
		'sale_price',
		'stock_quantity',
		'stock_status',
		'manage_stock',
		'weight',
		'category_ids',
		'tag_ids',
	);

	public function __construct( SyncQueue $queue ) {
		$this->queue = $queue;
	}

	public function init(): void {
		add_action( 'woocommerce_product_object_updated_props', array( $this, 'on_product_updated' ), 10, 2 );
		add_action( 'woocommerce_new_product', array( $this, 'on_product_created' ) );
		add_action( 'woocommerce_delete_product', array( $this, 'on_product_deleted' ) );
		add_action( 'woocommerce_delete_product_variation', array( $this, 'on_variation_deleted' ) );
	}

	/**
	 * @param \WC_Product $product
	 * @param string[]    $updated_props
	 */
	public function on_product_updated( \WC_Product $product, array $updated_props ): void {
		if ( ! $this->is_sync_enabled() ) {
			return;
		}

		if ( empty( array_intersect( $updated_props, self::WATCHED_PROPS ) ) ) {
			return;
		}

		$this->queue->enqueue_product( $product->get_id() );
	}

	public function on_product_created( int $product_id ): void {
		if ( $this->is_sync_enabled() ) {
			$this->queue->enqueue_product( $product_id );
		}
	}

	public function on_product_deleted( int $product_id ): void {
		/**
		 * Fires when a WooCommerce resource is deleted, so extensions can remove
		 * its mapped Sheets row. StoreSheet Pro listens and clears the row; the
		 * free tier has no listener, so the row simply remains.
		 *
		 * @since 1.0.0
		 * @param string $resource Resource type: product|variation|coupon.
		 * @param int    $id       Deleted object ID.
		 */
		do_action( 'storesheet_resource_deleted', 'product', $product_id );

		storesheet()->log( "Product {$product_id} deleted.", 'info' );
	}

	/**
	 * Fires the deletion seam for a product variation so Pro's RowRemover clears
	 * its Variations-tab row. WooCommerce deletes variations through a separate
	 * hook from parent products, so this must be wired independently.
	 *
	 * @param int $variation_id
	 */
	public function on_variation_deleted( int $variation_id ): void {
		/** This action is documented in includes/Hooks/ProductHooks.php */
		do_action( 'storesheet_resource_deleted', 'variation', $variation_id );

		storesheet()->log( "Variation {$variation_id} deleted.", 'info' );
	}

	private function is_sync_enabled(): bool {
		$settings = get_option( 'storesheet_settings', array() );
		return ! empty( $settings['sync_products'] ) && ! empty( $settings['spreadsheet_id'] );
	}
}
