<?php
/**
 * WooCommerce product type capabilities.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChangesWooCommerce\CoreCompat\WooCommerce;

/**
 * Discovers registered product types and exposes native behavior flags.
 */
final class ProductTypeCapabilities {
	/**
	 * @return array<string,string>
	 */
	public function registeredTypes(): array {
		return function_exists( 'wc_get_product_types' ) ? wc_get_product_types() : array();
	}

	/**
	 * @return array<string,bool>
	 */
	public function forProduct( \WC_Product $product ): array {
		$type = $product->get_type();

		return array(
			'attributes'         => ! $product instanceof \WC_Product_Variation,
			'cogs'               => $this->costOfGoodsEnabled(),
			'default_attributes' => method_exists( $product, 'get_default_attributes' )
				&& ! $product instanceof \WC_Product_Variation,
			'downloads'          => true,
			'external'           => 'external' === $type,
			'grouped_children'   => 'grouped' === $type && method_exists( $product, 'get_children' ),
			'inventory'          => ! in_array( $type, array( 'external', 'grouped' ), true ),
			'pos_visibility'     => ! $product instanceof \WC_Product_Variation
				&& taxonomy_exists( 'pos_product_visibility' ),
			'pricing'            => ! in_array( $type, array( 'variable', 'grouped' ), true )
				|| $product instanceof \WC_Product_Variation,
			'shipping'           => ! in_array( $type, array( 'external', 'grouped' ), true ),
			'variations'         => $product instanceof \WC_Product_Variable,
			'variation'          => $product instanceof \WC_Product_Variation,
		);
	}

	public function supports( \WC_Product $product, string $capability ): bool {
		return (bool) ( $this->forProduct( $product )[ $capability ] ?? false );
	}

	private function costOfGoodsEnabled(): bool {
		if ( ! function_exists( 'wc_get_container' ) ) {
			return false;
		}

		try {
			$controller_class = 'Automattic\\WooCommerce\\Internal\\CostOfGoodsSold\\CostOfGoodsSoldController';

			if ( ! class_exists( $controller_class ) ) {
				return false;
			}

			$controller = wc_get_container()->get( $controller_class );

			return is_callable( array( $controller, 'feature_is_enabled' ) )
				&& (bool) call_user_func( array( $controller, 'feature_is_enabled' ) );
		} catch ( \Throwable $exception ) {
			return false;
		}
	}
}
