<?php
/**
 * Product Type Schema Handler – business logic to retrieve schema and extracted fields.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync\includes\common\handlers
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

use MOMCS_Sync\Includes\Common\Services\Amazon\Product_Type_Service;
use WP_Error;

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

/**
 * Product Type Schema Handler.
 */
class Product_Type_Schema_Handler {
	/**
	 * Fetch product type schema and derived field lists.
	 *
	 * @param string $channel_id     Channel UUID.
	 * @param string $product_type   Amazon product type.
	 * @param string $marketplace_id Marketplace ID.
	 *
	 * @return array|WP_Error
	 */
	public function fetch_schema_and_fields( string $channel_id, string $product_type, string $marketplace_id ) {
		try {
			$service = new Product_Type_Service();

			$schema = $service->get_product_type_schema( $channel_id, $product_type, $marketplace_id );
			if ( is_wp_error( $schema ) ) {
				return $schema;
			}

			$all_fields          = $service->extract_all_fields( $schema );
			$hierarchical_fields = $service->extract_hierarchical_fields( $schema );
			$required_fields     = $service->extract_required_fields( $schema );

			return array(
				'schema'              => $schema,
				'all_fields'          => $all_fields,
				'hierarchical_fields' => $hierarchical_fields,
				'required_fields'     => $required_fields,
				'product_type'        => $product_type,
			);
		} catch ( \Throwable $e ) {
			return new WP_Error( 'momcs_sync_product_type_schema_error', 'Failed to fetch product type schema.' );
		}
	}
}
