<?php

namespace Dobare\Customer_Credit\API;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Customer_Credit\Dobare_Customer_Credit_Service;
use Dobare\Utils\Dobare_Utils;
use WP_REST_Request;
use WP_REST_Response;

class Dobare_Customer_Credit_REST_Controller extends Dobare_REST_Controller
{
	public function __construct()
	{
		$this->resource_name = 'customer-credit';
	}

	public function register_routes()
	{
		register_rest_route($this->namespace, '/' . $this->resource_name . '/', array(
			'methods'             => 'GET',
			'callback'            => array($this, 'get_customer_credit_details'),
			'permission_callback' => array($this, 'customer_credit_permissions_check'),
		));
	}

	/**
	 * Get customer credit details for the current user
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response
	 */
	public function get_customer_credit_details(WP_REST_Request $request)
	{
		$customer_credit_data = Dobare_Customer_Credit_Service::get_customer_credit_data();
		$normalized_response = Dobare_Utils::normalize_response_body($customer_credit_data, 200);

		return is_wp_error($normalized_response) ? $normalized_response : new WP_REST_Response($normalized_response, 200);
	}

	/**
	 * Ensure customer credit details can only be fetched with a valid REST nonce.
	 *
	 * @param WP_REST_Request $request Request instance.
	 *
	 * @return bool|\WP_Error
	 */
	public function customer_credit_permissions_check(WP_REST_Request $request)
	{
		$nonce = $request->get_header('X-WP-Nonce');

		if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) {
			return new \WP_Error(
				'rest_forbidden',
				esc_html__('Invalid security token.', 'dobare'),
				array('status' => 403)
			);
		}

		return true;
	}
}
