<?php
/**
 * Review Migration REST API Controller
 *
 * @package Ugcify\Admin\API
 */

namespace Ugcify\Admin\API;

use Ugcify\Migration\ReviewMigrationService;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_Error;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class ReviewMigrationAPI
 */
class ReviewMigrationAPI extends WP_REST_Controller {
	/**
	 * Namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'ugcify/v1';

	/**
	 * Rest base.
	 *
	 * @var string
	 */
	protected $rest_base = 'review-migration';

	/**
	 * Migration service.
	 *
	 * @var ReviewMigrationService
	 */
	private $service;

	/**
	 * Constructor.
	 */
	public function __construct() {
		require_once UGCIFY_PATH . 'includes/Review/ReviewMeta.php';
		require_once UGCIFY_PATH . 'includes/Migration/ReviewMigrationService.php';
		$this->service = new ReviewMigrationService();
	}

	/**
	 * Register routes.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/start',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'start' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/process',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'process' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/status/(?P<job_id>[\d]+)',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'status' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/cancel',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'cancel' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/retry-failed',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'retry_failed' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);
	}

	/**
	 * Permission callback.
	 *
	 * @return bool|WP_Error
	 */
	public function check_permission() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				__( 'Sorry, you are not allowed to access this resource.', 'ugcify' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Start migration.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function start( $request ) {
		$params    = $request->get_json_params();
		$direction = isset( $params['direction'] ) ? $params['direction'] : '';
		$options   = array(
			'batch_size' => isset( $params['batchSize'] ) ? (int) $params['batchSize'] : 100,
		);

		$result = $this->service->start_job( $direction, $options );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $result,
			)
		);
	}

	/**
	 * Process one batch.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function process( $request ) {
		$params = $request->get_json_params();
		$job_id = isset( $params['jobId'] ) ? (int) $params['jobId'] : 0;

		if ( $job_id <= 0 ) {
			return new WP_Error(
				'invalid_job_id',
				__( 'Invalid job ID.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		$result = $this->service->process_job( $job_id );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $result,
			)
		);
	}

	/**
	 * Get status.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function status( $request ) {
		$job_id = (int) $request->get_param( 'job_id' );

		if ( $job_id <= 0 ) {
			return new WP_Error(
				'invalid_job_id',
				__( 'Invalid job ID.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		$result = $this->service->get_job_snapshot( $job_id );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $result,
			)
		);
	}

	/**
	 * Cancel job.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function cancel( $request ) {
		$params = $request->get_json_params();
		$job_id = isset( $params['jobId'] ) ? (int) $params['jobId'] : 0;

		if ( $job_id <= 0 ) {
			return new WP_Error(
				'invalid_job_id',
				__( 'Invalid job ID.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		$result = $this->service->cancel_job( $job_id );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $result,
			)
		);
	}

	/**
	 * Retry failed items from a previous job.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function retry_failed( $request ) {
		$params = $request->get_json_params();
		$job_id = isset( $params['jobId'] ) ? (int) $params['jobId'] : 0;

		if ( $job_id <= 0 ) {
			return new WP_Error(
				'invalid_job_id',
				__( 'Invalid job ID.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		$result = $this->service->retry_failed( $job_id );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $result,
			)
		);
	}
}
