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

namespace MOWCPS\Common\Controllers\Rest_API;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use MOWCPS\Common\Abstracts\Base_Rest_Controller;
use MOWCPS\Common\Handlers\Rest_API\Authorization_Handler;
use MOWCPS\Common\Utils\Response_Builder;

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

/**
 * Class Authorization_Rest_Controller
 *
 * Handles authorization REST API callbacks
 */
class Authorization_Rest_Controller extends Base_Rest_Controller {
	/**
	 * Handler instance
	 *
	 * @var Authorization_Handler
	 */
	private $handler;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->handler = new Authorization_Handler();
	}

	/**
	 * Get authorization for a supplier
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_item( $request ) {
		$supplier_uuid = sanitize_key( wp_unslash( $request->get_param( 'supplier_uuid' ) ) );

		$authorization = $this->handler->get_by_supplier_uuid( $supplier_uuid );

		if ( is_wp_error( $authorization ) ) {
			return Response_Builder::from_wp_error( $authorization );
		}

		return Response_Builder::success( $authorization );
	}

	/**
	 * Create authorization for a supplier
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function create_item( $request ) {
		$supplier_uuid = sanitize_key( wp_unslash( $request->get_param( 'supplier_uuid' ) ) );
		$data          = $request->get_json_params();

		$authorization = $this->handler->create( $supplier_uuid, $data );

		if ( is_wp_error( $authorization ) ) {
			return Response_Builder::from_wp_error( $authorization );
		}

		return Response_Builder::success( $authorization, 201 );
	}

	/**
	 * Update authorization for a supplier
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_item( $request ) {
		$supplier_uuid = sanitize_key( wp_unslash( $request->get_param( 'supplier_uuid' ) ) );
		$data          = $request->get_json_params();

		$authorization = $this->handler->update( $supplier_uuid, $data );

		if ( is_wp_error( $authorization ) ) {
			return Response_Builder::from_wp_error( $authorization );
		}

		return Response_Builder::success( $authorization );
	}
}
