<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

use WP_Error;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;

/**
 * REST API Controller for AI Review endpoints
 *
 * Handles retry and status polling for AI reviews
 *
 * @since 4.2.9
 */
class REST_API_Controller extends WP_REST_Controller {

	/**
	 * The namespace of this controller's route.
	 *
	 * @since 4.2.9
	 *
	 * @var string
	 */
	protected $namespace = 'wpuf/v1';

	/**
	 * The base of this controller's route.
	 *
	 * @since 4.2.9
	 *
	 * @var string
	 */
	protected $rest_base = 'ai-review';

	/**
	 * Register the routes for the objects of the controller.
	 *
	 * @since 4.2.9
	 *
	 * @return void
	 */
	public function register_routes() {
		// Retry AI review endpoint
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/retry',
			[
				[
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => [ $this, 'retry_review' ],
					'permission_callback' => [ $this, 'retry_permission_check' ],
					'args'                => $this->get_retry_args(),
				],
			]
		);

		// Get review status endpoint
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/status',
			[
				[
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => [ $this, 'get_review_status' ],
					'permission_callback' => [ $this, 'status_permission_check' ],
					'args'                => $this->get_status_args(),
				],
			]
		);
	}

	/**
	 * Check if a given request has access to retry AI review.
	 *
	 * @since 4.2.9
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 *
	 * @return WP_Error|bool
	 */
	public function retry_permission_check( $request ) {
		// Nonce check is handled by WordPress REST API automatically via X-WP-Nonce header

		// Check if user has permission to retry reviews
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to retry AI reviews.', 'wpuf-pro' ),
				[ 'status' => 403 ]
			);
		}

		return true;
	}

	/**
	 * Check if a given request has access to get AI review status.
	 *
	 * @since 4.2.9
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 *
	 * @return WP_Error|bool
	 */
	public function status_permission_check( $request ) {
		// Nonce check is handled by WordPress REST API automatically via X-WP-Nonce header

		// Check if user has permission to view posts
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to view AI review status.', 'wpuf-pro' ),
				[ 'status' => 403 ]
			);
		}

		return true;
	}

	/**
	 * Retry AI review for a post.
	 *
	 * @since 4.2.9
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function retry_review( $request ) {
		$post_id = $request->get_param( 'post_id' );

		if ( empty( $post_id ) ) {
			return new WP_Error(
				'invalid_post_id',
				__( 'Invalid post ID.', 'wpuf-pro' ),
				[ 'status' => 400 ]
			);
		}

		// Pass false for verify_nonce since REST API handles nonce verification via X-WP-Nonce header
		$result = Retry_Handler::handle_manual_retry( $post_id, false );

		if ( $result['success'] ) {
			return rest_ensure_response(
				[
					'success' => true,
					'message' => $result['message'],
				]
			);
		}

		return new WP_Error(
			'retry_failed',
			$result['message'],
			[ 'status' => 400 ]
		);
	}

	/**
	 * Get AI review status for a post.
	 *
	 * @since 4.2.9
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_review_status( $request ) {
		$post_id = $request->get_param( 'post_id' );

		if ( empty( $post_id ) ) {
			return new WP_Error(
				'invalid_post_id',
				__( 'Invalid post ID.', 'wpuf-pro' ),
				[ 'status' => 400 ]
			);
		}

		$status = get_post_meta( $post_id, 'wpuf_ai_review_status', true );
		$review = get_post_meta( $post_id, 'wpuf_ai_post_review', true );
		$summary = ( $review && isset( $review['summary'] ) ) ? $review['summary'] : '';

		return rest_ensure_response(
			[
				'success' => true,
				'status'  => $status,
				'summary' => $summary,
			]
		);
	}

	/**
	 * Get arguments for retry endpoint.
	 *
	 * @since 4.2.9
	 *
	 * @return array
	 */
	private function get_retry_args() {
		return [
			'post_id' => [
				'required'          => true,
				'type'              => 'integer',
				'description'       => __( 'The post ID to retry AI review for.', 'wpuf-pro' ),
				'validate_callback' => function( $value ) {
					return is_numeric( $value ) && $value > 0;
				},
				'sanitize_callback' => 'absint',
			],
		];
	}

	/**
	 * Get arguments for status endpoint.
	 *
	 * @since 4.2.9
	 *
	 * @return array
	 */
	private function get_status_args() {
		return [
			'post_id' => [
				'required'          => true,
				'type'              => 'integer',
				'description'       => __( 'The post ID to get AI review status for.', 'wpuf-pro' ),
				'validate_callback' => function( $value ) {
					return is_numeric( $value ) && $value > 0;
				},
				'sanitize_callback' => 'absint',
			],
		];
	}
}
