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

namespace MOWCPS\Common\Utils;

use WP_REST_Response;
use WP_Error;

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

/**
 * Class Response_Builder
 *
 * Builds standardized REST API responses
 */
class Response_Builder {
	/**
	 * Build a success response
	 *
	 * @param mixed $data     Response data.
	 * @param int   $status   HTTP status code.
	 * @param array $headers  Response headers.
	 * @return WP_REST_Response
	 */
	public static function success( $data, $status = 200, $headers = array() ) {
		$response = array(
			'success' => $data['success'] ?? true,
			'data'    => $data['data'] ?? $data,
		);

		if ( isset( $data['message'] ) ) {
			$response['message'] = $data['message'];
		}

		$status = $data['status_code'] ?? $status;

		return new WP_REST_Response( $response, $status, $headers );
	}

	/**
	 * Build an error response
	 *
	 * @param string $code     Error code.
	 * @param string $message  Error message.
	 * @param array  $data     Error data.
	 * @param int    $status   HTTP status code.
	 * @param array  $headers  Response headers.
	 * @return WP_REST_Response
	 */
	public static function error( $code, $message, $data = array(), $status = 400, $headers = array() ) {
		$response = array(
			'success' => false,
			'error'   => array(
				'code'    => $code,
				'message' => $message,
			),
		);

		$status = $data['status_code'] ?? $status;

		return new WP_REST_Response( $response, $status, $headers );
	}

	/**
	 * Build a response from a WP_Error object
	 *
	 * @param WP_Error $wp_error WP_Error object.
	 * @param int      $status   HTTP status code (optional).
	 * @param array    $headers  Response headers (optional).
	 * @return WP_REST_Response
	 */
	public static function from_wp_error( $wp_error, $status = null, $headers = array() ) {
		$error_data = $wp_error->get_error_data();
		$status     = $status ?? ( isset( $error_data['status'] ) ? $error_data['status'] : 400 );

		$response = array(
			'success' => false,
			'error'   => array(
				'code'    => $wp_error->get_error_code(),
				'message' => $wp_error->get_error_message(),
				'data'    => $error_data,
			),
		);

		return new WP_REST_Response( $response, $status, $headers );
	}

	/**
	 * Build a deleted response
	 *
	 * @param array $headers Response headers.
	 * @return WP_REST_Response
	 */
	public static function deleted( $headers = array() ) {
		return new WP_REST_Response(
			array(
				'success' => true,
				'message' => __( 'Item deleted successfully.', 'products-sync-for-woocommerce' ),
			),
			200,
			$headers
		);
	}
}
