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

namespace MOWCPS\Common\Abstracts;

use WP_REST_Request;
use WP_Error;
use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Utils\Response_Builder;

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

/**
 * Abstract Class Base_Rest_Controller
 *
 * Base class for REST API controllers with common permission checks
 */
abstract class Base_Rest_Controller {
	/**
	 * Check if user has permission to perform REST operations
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return bool|WP_Error
	 */
	public function check_permissions( $request ) {
		// Verify nonce first.
		$nonce = $request->get_header( 'X-WP-Nonce' );
		if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
			return new WP_Error(
				Constants::ERROR_INVALID_NONCE,
				Constants::MSG_INVALID_NONCE,
				array( 'status' => Constants::HTTP_UNAUTHORIZED )
			);
		}

		// Then check user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				Constants::ERROR_REST_FORBIDDEN,
				Constants::MSG_REST_FORBIDDEN,
				array( 'status' => Constants::HTTP_FORBIDDEN )
			);
		}

		return true;
	}

	/**
	 * Handle API response in a standardized way
	 *
	 * @param mixed  $result         Result from handler method.
	 * @param string $success_message Optional success message.
	 * @return WP_REST_Response|WP_Error Response object or error.
	 */
	protected function handle_api_response( $result, $success_message = null ) {
		if ( is_wp_error( $result ) ) {
			return Response_Builder::from_wp_error( $result );
		}

		return $success_message ? Response_Builder::success( $success_message, $result ) : Response_Builder::success( $result );
	}
}
