<?php
/**
 * Sync Request DTO
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage DTO
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\DTO;

use WP_Error;
use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Abstracts\Base_DTO;
use MOWCPS\Common\Utils\Utils;

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

/**
 * Class Sync_Request
 *
 * Handles sync request data transformation and validation
 */
class Sync_Request extends Base_DTO {
	/**
	 * Sync action
	 *
	 * @var string
	 */
	private $action;

	/**
	 * Sync data
	 *
	 * @var array
	 */
	private $attribute_mapping_ids;

	/**
	 * Valid sync actions
	 *
	 * @var array
	 */
	private static $valid_actions = array(
		Constants::SYNC_ACTION_START,
		Constants::SYNC_ACTION_PAUSE,
		Constants::SYNC_ACTION_RESUME,
		Constants::SYNC_ACTION_ABORT,
	);

	/**
	 * Create instance from request parameters
	 *
	 * @param array $params Request parameters.
	 * @return self|WP_Error Instance or error if validation fails
	 */
	public static function from_request_parameters( $params ) {
		$instance = new self();

		// Transform data.
		$instance->action                = sanitize_text_field( wp_unslash( $params['action'] ?? '' ) );
		$instance->attribute_mapping_ids = isset( $params['attribute_mapping_ids'] ) ? array_map( 'sanitize_text_field', wp_unslash( $params['attribute_mapping_ids'] ) ) : null;

		// Validate the data.
		$validation_result = $instance->validate();
		if ( is_wp_error( $validation_result ) ) {
			return $validation_result;
		}

		return $instance;
	}

	/**
	 * Validate the request data
	 *
	 * @return true|WP_Error True if valid, WP_Error if invalid
	 */
	protected function validate() {
		// Validate action.
		if ( empty( $this->action ) ) {
			return new WP_Error(
				Constants::ERROR_MISSING_REQUIRED_FIELD,
				sprintf( Constants::MSG_MISSING_REQUIRED_FIELD, 'action' ),
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		if ( ! in_array( $this->action, self::$valid_actions, true ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_FIELD_VALUE,
				sprintf( Constants::MSG_INVALID_FIELD_VALUE, 'action' ),
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		// Validate attribute mapping IDs.
		if ( null !== $this->attribute_mapping_ids && ! is_array( $this->attribute_mapping_ids ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_CONFIGURATION,
				'Invalid attribute mapping IDs format. Must be an array.',
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		return true;
	}

	/**
	 * Convert to array
	 *
	 * @return array
	 */
	public function to_array() {
		return array(
			'action'                => $this->action,
			'attribute_mapping_ids' => $this->attribute_mapping_ids,
		);
	}
}
