<?php
/**
 * Square Catalog helpers (SKU → item variation lookup).
 *
 * @package SHC4WC
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class SHC4WC_Catalog {
	const SKU_CACHE_PREFIX = 'shc4wc_catalog_sku_';
	const SKU_CACHE_TTL    = 300;
	const SKU_MISS         = '__none__';

	/**
	 * Resolve a Square CatalogItemVariation id by SKU (cached per SKU).
	 *
	 * @param string $sku WooCommerce product SKU.
	 * @return string Catalog variation id or empty when not found.
	 */
	public static function find_variation_id_by_sku( $sku ) {
		$sku = trim( (string) $sku );
		if ( '' === $sku ) {
			return '';
		}

		if ( ! SHC4WC_Plugin::is_connected() ) {
			return '';
		}

		$cache_key = self::SKU_CACHE_PREFIX . md5( strtolower( $sku ) );
		$cached    = get_transient( $cache_key );
		if ( is_string( $cached ) ) {
			return self::SKU_MISS === $cached ? '' : $cached;
		}

		$api      = new SHC4WC_API( SHC4WC_Plugin::get_settings() );
		$response = $api->search_catalog_variation_by_sku( $sku );
		$id       = '';

		if ( ! is_wp_error( $response ) && ! empty( $response['objects'][0]['id'] ) ) {
			$id = sanitize_text_field( (string) $response['objects'][0]['id'] );
		}

		set_transient( $cache_key, '' !== $id ? $id : self::SKU_MISS, self::SKU_CACHE_TTL );

		if ( '' !== $id && ! empty( SHC4WC_Plugin::get_settings()['debug'] ) && 'yes' === SHC4WC_Plugin::get_settings()['debug'] ) {
			$api->log(
				'Square catalog SKU matched',
				array(
					'sku'                 => $sku,
					'catalog_object_id'   => $id,
				)
			);
		}

		return $id;
	}
}
