<?php
/**
 * Discoverable product taxonomy catalog.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChangesWooCommerce\CoreCompat\Discovery;

/**
 * Filters internal taxonomies from product-facing taxonomy discovery.
 */
final class TaxonomyCatalog {
	/**
	 * @var string[]
	 */
	private const INTERNAL = array(
		'product_type',
		'product_visibility',
		'product_shipping_class',
		'pos_product_visibility',
	);

	/**
	 * @return array<string,\WP_Taxonomy>
	 */
	public function productTaxonomies(): array {
		$taxonomies = get_object_taxonomies( 'product', 'objects' );
		$discovered = array();

		foreach ( $taxonomies as $name => $taxonomy ) {
			if (
				! $taxonomy instanceof \WP_Taxonomy
				|| in_array( $name, self::INTERNAL, true )
				|| (
					! $taxonomy->public
					&& ! $taxonomy->show_ui
					&& strncmp( $name, 'pa_', strlen( 'pa_' ) ) !== 0
					&& 'product_shipping_class' !== $name
				)
			) {
				continue;
			}

			$discovered[ $name ] = $taxonomy;
		}

		ksort( $discovered );

		return $discovered;
	}

	public function versionFingerprint(): string {
		$summary = array();

		foreach ( $this->productTaxonomies() as $name => $taxonomy ) {
			$summary[ $name ] = array(
				'public'       => (bool) $taxonomy->public,
				'show_ui'      => (bool) $taxonomy->show_ui,
				'show_in_rest' => (bool) $taxonomy->show_in_rest,
				'hierarchical' => (bool) $taxonomy->hierarchical,
				'sort'         => (bool) $taxonomy->sort,
			);
		}

		return substr( hash( 'sha256', (string) wp_json_encode( $summary ) ), 0, 12 );
	}
}
