<?php
/**
 * Variation structure module identity.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Variations;

use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Attributes\ProductAttributesModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Downloads\DownloadableProductModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Identity\ProductIdentityModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Inventory\InventoryModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Media\ProductMediaModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Pricing\PricingModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Shipping\ShippingModule;
use ScheduledChangesWooCommerce\CoreCompat\WooCommerce\Tax\TaxModule;

/** Identifies variation creation and structure lifecycle capability. */
final class VariationStructureModule {
	public const MODULE_ID = 'scheduled-changes-variation-structure';

	/** Creates the retry-safe WooCommerce variation lifecycle service. */
	public function createService(): VariationService {
		return new VariationService();
	}

	/**
	 * Returns the exact modules required by one structural variation payload.
	 *
	 * @param array<string,string> $attributes Variation attributes.
	 * @param array<string,mixed>  $values Variation field values.
	 * @return string[]
	 */
	public function requiredModules( array $attributes, array $values ): array {
		$required = array( ProductIdentityModule::MODULE_ID, self::MODULE_ID );

		if ( array() !== $attributes ) {
			$required[] = ProductAttributesModule::MODULE_ID;
		}

		$families = array(
			PricingModule::MODULE_ID             => array( 'regular_price', 'sale_price', 'sale_start', 'sale_end' ),
			InventoryModule::MODULE_ID           => array( 'manage_stock', 'stock_quantity', 'stock_status', 'backorders' ),
			ShippingModule::MODULE_ID            => array( 'weight', 'length', 'width', 'height', 'shipping_class_id' ),
			TaxModule::MODULE_ID                 => array( 'tax_class' ),
			ProductMediaModule::MODULE_ID        => array( 'image_id' ),
			DownloadableProductModule::MODULE_ID => array( 'downloadable', 'virtual', 'downloads', 'download_limit', 'download_expiry' ),
		);

		foreach ( $families as $module_id => $keys ) {
			if ( array_intersect( $keys, array_keys( $values ) ) ) {
				$required[] = $module_id;
			}
		}

		$required = array_values( array_unique( $required ) );
		sort( $required );

		return $required;
	}
}
