<?php
/**
 * Authorization 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 Authorization_Request
 *
 * Handles authorization request data transformation and validation
 */
class Authorization_Request extends Base_DTO {
	/**
	 * Authorization type
	 *
	 * @var string
	 */
	private $auth_type;

	/**
	 * Authorization settings
	 *
	 * @var array|null
	 */
	private $auth_settings;

	/**
	 * Valid auth types
	 *
	 * @var array
	 */
	private static $valid_auth_types = array(
		Constants::AUTH_TYPE_NO_AUTH,
		Constants::AUTH_TYPE_BASIC,
		Constants::AUTH_TYPE_BEARER,
		Constants::AUTH_TYPE_API_KEY,
		Constants::AUTH_TYPE_OAUTH2,
		Constants::AUTH_TYPE_CUSTOM,
	);

	/**
	 * 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->auth_type = sanitize_text_field( wp_unslash( $params['auth_type'] ?? Constants::AUTH_TYPE_NO_AUTH ) );

		// For no-auth, always set auth_settings to null regardless of input.
		if ( Constants::AUTH_TYPE_NO_AUTH === $instance->auth_type ) {
			$instance->auth_settings = null;
		} else {
			$instance->auth_settings = isset( $params['auth_settings'] ) ? Utils::sanitize_json_field( wp_unslash( $params['auth_settings'] ) ) : null;
		}

		return $instance->validate();
	}

	/**
	 * Validate the request data
	 *
	 * @return self|WP_Error Instance if valid, WP_Error if invalid
	 */
	protected function validate() {
		// Validate auth_type.
		if ( ! in_array( $this->auth_type, self::$valid_auth_types, true ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_AUTH_TYPE,
				Constants::MSG_INVALID_AUTH_TYPE,
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		// Validate auth_settings if provided.
		if ( null !== $this->auth_settings && ! is_array( $this->auth_settings ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_AUTH_SETTINGS,
				Constants::MSG_INVALID_AUTH_SETTINGS,
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		return $this;
	}

	/**
	 * Convert to array for database
	 *
	 * @return array Data ready for database
	 */
	public function to_array() {
		return array(
			'auth_type'     => $this->auth_type,
			'auth_settings' => $this->auth_settings,
		);
	}
}
