<?php
/**
 * The Search Rest Controller class.
 * Registers the REST routes for Search.
 *
 * @package automattic/jetpack-search
 */

namespace Automattic\Jetpack\Search;

use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Rest_Authentication;
use Automattic\Jetpack\My_Jetpack\Products\Search as Search_Product;
use Automattic\Jetpack\My_Jetpack\Products\Search_Stats as Search_Product_Stats;
use Jetpack_Options;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

if ( ! defined( 'ABSPATH' ) ) {
	exit( 0 );
}

/**
 * Registers the REST routes for Search.
 */
class REST_Controller {
	/**
	 * Namespace for the REST API.
	 *
	 * This is overriden with value `wpcom-orgin/jetpack/v4` for WPCOM.
	 *
	 * @var string
	 */
	public static $namespace = 'jetpack/v4';
	/**
	 * Whether it's run on WPCOM.
	 *
	 * @var bool
	 */
	protected $is_wpcom;

	/**
	 * Module Control object.
	 *
	 * @var Module_Control
	 */
	protected $search_module;

	/**
	 * Plan object.
	 *
	 * @var Plan
	 */
	public $plan;

	/**
	 * Constructor
	 *
	 * @param bool                $is_wpcom - Whether it's run on WPCOM.
	 * @param Module_Control|null $module_control - Module_Control object if any.
	 * @param Plan|null           $plan - Plan object if any.
	 */
	public function __construct( $is_wpcom = false, $module_control = null, $plan = null ) {
		$this->is_wpcom      = $is_wpcom;
		$this->search_module = $module_control === null ? new Module_Control() : $module_control;
		$this->plan          = $plan === null ? new Plan() : $plan;
	}

	/**
	 * Registers the REST routes on the `rest_api_init` hook.
	 *
	 * Instantiated here, rather than eagerly, so the controller class only loads
	 * on requests that reach `rest_api_init`. Static so the callback can be
	 * unregistered.
	 *
	 * @access public
	 */
	public static function register() {
		( new self() )->register_rest_routes();
	}

	/**
	 * Registers the REST routes for Search.
	 *
	 * @access public
	 * @static
	 */
	public function register_rest_routes() {
		$this->register_common_rest_routes();
		if ( ! Helper::is_wpcom() ) {
			$this->register_jetpack_only_rest_routes();
		} else {
			$this->register_wpcom_only_rest_routes();
		}
	}

	/**
	 * Routes both existing in Jetpack and WPCOM simple sites.
	 */
	protected function register_common_rest_routes() {
		register_rest_route(
			static::$namespace,
			'/search/plan',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_search_plan' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/settings',
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'update_settings' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/settings',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_settings' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/stats',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_stats' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/pricing',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'product_pricing' ),
				'permission_callback' => 'is_user_logged_in',
			)
		);
		// "Restore default" for the singleton-template CPTs. Lives on
		// jetpack/v4 (not /wp/v2/<rest_base>) so wpcom-origin can proxy it
		// on Simple sites — the Jetpack-registered CPT controller isn't on
		// the wpcom REST surface. The allowed `<post_type>` slugs are
		// enforced inside the handler (single source of truth) rather than
		// duplicated into a route-level validate_callback.
		register_rest_route(
			static::$namespace,
			'/search/templates/(?P<post_type>[a-z0-9_-]+)',
			array(
				'methods'             => WP_REST_Server::DELETABLE,
				'callback'            => array( $this, 'reset_singleton_template' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
				'args'                => array(
					'post_type' => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_key',
					),
				),
			)
		);
	}

	/**
	 * Routes only existing in Jetpack.
	 */
	protected function register_jetpack_only_rest_routes() {
		register_rest_route(
			static::$namespace,
			'/search/plan/activate',
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'activate_plan' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/plan/deactivate',
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'deactivate_plan' ),
				'permission_callback' => array( $this, 'require_admin_privilege_callback' ),
			)
		);
		register_rest_route(
			static::$namespace,
			'/search',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_search_results' ),
				'permission_callback' => 'is_user_logged_in',
			)
		);
		register_rest_route(
			static::$namespace,
			'/search/local-stats',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_local_stats' ),
				'permission_callback' => array( $this, 'require_valid_blog_token_callback' ),
			)
		);
	}

	/**
	 * Routes only existing in WPCOM.
	 *
	 * We currently don't have any.
	 */
	protected function register_wpcom_only_rest_routes() {
		return true;
	}

	/**
	 * Only administrators can access the API.
	 *
	 * @return bool|WP_Error True if a blog token was used to sign the request, WP_Error otherwise.
	 */
	public function require_admin_privilege_callback() {
		if ( current_user_can( 'manage_options' ) ) {
			return true;
		}

		return $this->get_forbidden_error();
	}

	/**
	 * The corresponding endpoints can only be accessible from WPCOM.
	 *
	 * @access public
	 * @static
	 *
	 * @return bool|WP_Error True if a blog token was used to sign the request, WP_Error otherwise.
	 */
	public function require_valid_blog_token_callback() {
		if ( Rest_Authentication::is_signed_with_blog_token() ) {
			return true;
		}

		return $this->get_forbidden_error();
	}

	/**
	 * Return a WP_Error object with a forbidden error.
	 */
	protected function get_forbidden_error() {
		$error_msg = esc_html__(
			'You are not allowed to perform this action.',
			'jetpack-search-pkg'
		);

		return new WP_Error( 'rest_forbidden', $error_msg, array( 'status' => rest_authorization_required_code() ) );
	}

	/**
	 * Proxy the request to WPCOM and return the response.
	 *
	 * GET `jetpack/v4/search/plan`
	 */
	public function get_search_plan() {
		$response = ( new Plan() )->get_plan_info_from_wpcom();
		return $this->make_proper_response( $response );
	}

	/**
	 * POST `jetpack/v4/search/settings`
	 *
	 * @param WP_REST_Request $request - REST request.
	 */
	public function update_settings( $request ) {
		$request_body = $request->get_json_params();
		if ( ! is_array( $request_body ) ) {
			$request_body = array();
		}

		$module_active                 = isset( $request_body['module_active'] ) ? (bool) $request_body['module_active'] : null;
		$instant_search_enabled        = isset( $request_body['instant_search_enabled'] ) ? (bool) $request_body['instant_search_enabled'] : null;
		$swap_classic_to_inline_search = isset( $request_body['swap_classic_to_inline_search'] ) ? (bool) $request_body['swap_classic_to_inline_search'] : null;
		$experience                    = isset( $request_body['experience'] ) && is_string( $request_body['experience'] )
			? sanitize_text_field( $request_body['experience'] )
			: null;
		$reader_chat                   = array_key_exists( 'reader_chat', $request_body ) ? (bool) $request_body['reader_chat'] : null;
		$ai_answers_enabled            = isset( $request_body['ai_answers_enabled'] ) ? (bool) $request_body['ai_answers_enabled'] : null;

		$search_suggestions_enabled = isset( $request_body['search_suggestions_enabled'] ) ? (bool) $request_body['search_suggestions_enabled'] : null;

		$override_woocommerce_search_template = isset( $request_body['override_woocommerce_search_template'] ) ? (bool) $request_body['override_woocommerce_search_template'] : null;

		$error = $this->validate_search_settings( $module_active, $instant_search_enabled, $swap_classic_to_inline_search, $experience, $reader_chat, $ai_answers_enabled, $search_suggestions_enabled, $override_woocommerce_search_template );

		if ( is_wp_error( $error ) ) {
			return $error;
		}

		// If an experience value was provided, delegate to Module_Control::update_experience(),
		// which encapsulates the storage shape (off → module deactivate, inline → delete option,
		// embedded/overlay → write affirmative value) and keeps the legacy booleans in lockstep.
		if ( $experience !== null ) {
			$result = $this->search_module->update_experience( $experience );
			if ( is_wp_error( $result ) ) {
				return $result;
			}
			return rest_ensure_response( $this->get_settings() );
		}

		// Enabling instant search should enable the module too.
		if ( true === $instant_search_enabled && true !== $module_active ) {
			$module_active = true;
		}

		$errors = array();
		if ( $module_active !== null ) {
			$module_active_updated = $this->search_module->update_status( $module_active );
			if ( is_wp_error( $module_active_updated ) ) {
				$errors['module_active'] = $module_active_updated;
			}
		}

		if ( $instant_search_enabled !== null ) {
			$instant_search_enabled_updated = $this->search_module->update_instant_search_status( $instant_search_enabled );
			if ( is_wp_error( $instant_search_enabled_updated ) ) {
				$errors['instant_search_enabled'] = $instant_search_enabled_updated;
			}
		}

		if ( $swap_classic_to_inline_search !== null ) {
			$this->search_module->update_swap_classic_to_inline_search( $swap_classic_to_inline_search );
		}

		if ( $reader_chat !== null ) {
			update_option( 'reader_chat', $reader_chat );
		}

		if ( $ai_answers_enabled !== null ) {
			update_option( 'jetpack_search_ai_answers_enabled', $ai_answers_enabled );
		}
		if ( $search_suggestions_enabled !== null ) {
			update_option( 'jetpack_search_suggestions_enabled', $search_suggestions_enabled );
		}
		if ( $override_woocommerce_search_template !== null ) {
			update_option( 'jetpack_search_override_woocommerce_search_template', $override_woocommerce_search_template );
		}

		if ( ! empty( $errors ) ) {
			return new WP_Error(
				'some_updated',
				sprintf(
					/* translators: %s are the setting name that not updated. */
					__( 'Some settings ( %s ) not updated.', 'jetpack-search-pkg' ),
					implode(
						',',
						array_keys( $errors )
					)
				),
				array( 'status' => 400 )
			);
		}

		return rest_ensure_response( $this->get_settings() );
	}

	/**
	 * Validate $module_active and $instant_search_enabled. Returns an WP_Error instance if invalid.
	 *
	 * @param boolean     $module_active - Module status.
	 * @param boolean     $instant_search_enabled - Instant Search status.
	 * @param boolean     $swap_classic_to_inline_search - New inline search status.
	 * @param string|null $experience - Experience value.
	 * @param bool|null   $reader_chat - Reader Chat status.
	 * @param bool|null   $ai_answers_enabled - Whether Jetpack Search AI answers is enabled.
	 * @param bool|null   $search_suggestions_enabled - New search suggestions status.
	 * @param bool|null   $override_woocommerce_search_template - New WooCommerce search-template override status.
	 */
	protected function validate_search_settings( $module_active, $instant_search_enabled, $swap_classic_to_inline_search, $experience = null, $reader_chat = null, $ai_answers_enabled = null, $search_suggestions_enabled = null, $override_woocommerce_search_template = null ) {
		if ( $reader_chat !== null && ! $this->is_reader_chat_setting_registered() ) {
			return new WP_Error(
				'rest_invalid_arguments',
				esc_html__( 'The arguments passed in are invalid.', 'jetpack-search-pkg' ),
				array( 'status' => 400 )
			);
		}

		// `experience` is the canonical source of truth and writes the legacy booleans in lockstep.
		// Reject requests that mix it with any other settings field so callers don't silently
		// lose those fields — the `experience` branch in update_settings() early-returns and
		// would otherwise drop them.
		if ( $experience !== null ) {
			if ( $module_active !== null || $instant_search_enabled !== null || $swap_classic_to_inline_search !== null || $reader_chat !== null || $ai_answers_enabled !== null || $search_suggestions_enabled !== null || $override_woocommerce_search_template !== null ) {
				return new WP_Error(
					'rest_invalid_arguments',
					esc_html__( 'The `experience` field cannot be combined with `module_active`, `instant_search_enabled`, `swap_classic_to_inline_search`, `reader_chat`, `ai_answers_enabled`, `search_suggestions_enabled`, or `override_woocommerce_search_template`.', 'jetpack-search-pkg' ),
					array( 'status' => 400 )
				);
			}
			return true;
		}
		if (
			$module_active === null &&
			$instant_search_enabled === null &&
			( $swap_classic_to_inline_search !== null || $reader_chat !== null )
		) {
			// Allow updating auxiliary settings without updating/validating the module settings.
			return true;
		}
		if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $ai_answers_enabled !== null ) {
			// allow updating 'ai_answers_enabled' without updating/validating other settings.
			return true;
		}
		if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $search_suggestions_enabled !== null ) {
			// allow updating 'search_suggestions_enabled' without updating/validating other settings.
			return true;
		}
		if ( $module_active === null && $instant_search_enabled === null && $swap_classic_to_inline_search === null && $override_woocommerce_search_template !== null ) {
			// allow updating 'override_woocommerce_search_template' without updating/validating other settings.
			return true;
		}
		if ( ( true === $instant_search_enabled && false === $module_active ) || ( $module_active === null && $instant_search_enabled === null ) ) {
			return new WP_Error(
				'rest_invalid_arguments',
				esc_html__( 'The arguments passed in are invalid.', 'jetpack-search-pkg' ),
				array( 'status' => 400 )
			);
		}
		return true;
	}

		/**
		 *     GET `jetpack/v4/search/settings`
		 */
	public function get_settings() {
		$settings = array(
			'module_active'                        => $this->search_module->is_active(),
			'instant_search_enabled'               => $this->search_module->is_instant_search_enabled(),
			'swap_classic_to_inline_search'        => $this->search_module->is_swap_classic_to_inline_search(),
			'experience'                           => $this->search_module->get_experience(),
			'ai_answers_enabled'                   => AI_Answers::is_enabled(),
			'search_suggestions_enabled'           => (bool) get_option( 'jetpack_search_suggestions_enabled', false ),
			'override_woocommerce_search_template' => Search_Blocks::woocommerce_search_template_override_enabled(),
		);

		if ( $this->is_reader_chat_setting_registered() ) {
			$settings['reader_chat'] = (bool) get_option( 'reader_chat', false );
		}

		return rest_ensure_response( $settings );
	}

	/**
	 * Check whether Reader Chat is available through REST settings in this request.
	 *
	 * Reader Chat registers `reader_chat` only for proxied rollout contexts, so the
	 * Search dashboard should expose the toggle only when that setting exists.
	 *
	 * @return bool True when reader_chat is registered.
	 */
	protected function is_reader_chat_setting_registered() {
		return array_key_exists( 'reader_chat', get_registered_settings() );
	}

	/**
	 * Proxy the request to WPCOM and return the response.
	 *
	 * GET `jetpack/v4/search/stats`
	 */
	public function get_stats() {
		$response = ( new Stats() )->get_stats_from_wpcom();
		return $this->make_proper_response( $response );
	}

	/**
	 * Search Endpoint for private sites.
	 *
	 * GET `jetpack/v4/search`
	 *
	 * @param WP_REST_Request $request - REST request.
	 */
	public function get_search_results( $request ) {
		$blog_id  = $this->get_blog_id();
		$path     = sprintf( '/sites/%d/search', absint( $blog_id ) );
		$path     = add_query_arg(
			$request->get_query_params(),
			sprintf( '/sites/%d/search', absint( $blog_id ) )
		);
		$response = Client::wpcom_json_api_request_as_blog( $path, '1.3', array(), null, 'rest' );
		return rest_ensure_response( $this->make_proper_response( $response ) );
	}

	/**
	 * Activate plan: activate the search module, instant search and do initial configuration.
	 * Typically called from WPCOM.
	 *
	 * POST `jetpack/v4/search/plan/activate`
	 *
	 * @param WP_REST_Request $request - REST request.
	 */
	public function activate_plan( $request ) {
		$default_options = array(
			'search_plan_info'      => null,
			'enable_search'         => true,
			'enable_instant_search' => true,
			'search_experience'     => null,
			'auto_config_search'    => true,
		);
		$payload         = $request->get_json_params();
		$payload         = wp_parse_args( $payload, $default_options );

		// Update plan data, plan info is in the request body.
		// We do this to avoid another call to WPCOM and reduce latency.
		if ( $payload['search_plan_info'] === null || ! $this->plan->set_plan_options( $payload['search_plan_info'] ) ) {
			$this->plan->get_plan_info_from_wpcom();
		}

		// Enable search module by default, unless `enable_search` is explicitly set to boolean `false`.
		if ( false !== $payload['enable_search'] ) {
			$ret = $this->search_module->activate();
			if ( is_wp_error( $ret ) ) {
				return $ret;
			}
		}

		if ( $payload['search_experience'] !== null ) {
			// Canonical path. Restrict to activate-able experiences — `off`
			// belongs on `/plan/deactivate`, and a non-string payload would
			// blow up `update_experience(string $experience)`.
			$valid_experiences = array(
				Module_Control::EXPERIENCE_OVERLAY,
				Module_Control::EXPERIENCE_INLINE,
				Module_Control::EXPERIENCE_EMBEDDED,
			);
			if ( ! is_string( $payload['search_experience'] )
				|| ! in_array( $payload['search_experience'], $valid_experiences, true )
			) {
				return new WP_Error(
					'invalid_experience',
					__( 'Invalid experience value.', 'jetpack-search-pkg' ),
					array( 'status' => 400 )
				);
			}
			$ret = $this->search_module->update_experience( sanitize_text_field( $payload['search_experience'] ) );
			if ( is_wp_error( $ret ) ) {
				return $ret;
			}
		}

		if ( $payload['search_experience'] === null && false !== $payload['enable_instant_search'] ) {
			// Legacy path: old WPCOM callers send `enable_instant_search`
			// instead of `search_experience`. Gated on the canonical value
			// being absent so it doesn't overwrite a non-overlay experience
			// the caller just set.
			// Error handling intentionally skipped — this is the legacy fallback.
			$ret = $this->search_module->enable_instant_search();
		}

		// `auto_config_search` wires up Overlay sidebar widgets — only meaningful
		// when Overlay is the resulting experience. For Inline / Embedded, the
		// caller would otherwise get widget side effects they didn't ask for.
		if ( false !== $payload['auto_config_search'] && $this->search_module->is_instant_search_enabled() ) {
			Instant_Search::instance( $this->get_blog_id() )->auto_config_search();
		}

		return rest_ensure_response(
			array(
				'code' => 'success',
			)
		);
	}

	/**
	 * Deactivate plan: turn off search module and instant search.
	 * If the plan is still valid then the function would simply deactivate the search module.
	 * Typically called from WPCOM.
	 *
	 * POST `jetpack/v4/search/plan/deactivate`
	 */
	public function deactivate_plan() {
		// Instant Search would be disabled along with search module.
		$this->search_module->deactivate();
		return rest_ensure_response(
			array(
				'code' => 'success',
			)
		);
	}

	/**
	 * Return post type breakdown for the site.
	 */
	public function get_local_stats() {
		return array(
			'post_count'          => Search_Product_Stats::estimate_count(),
			'post_type_breakdown' => Search_Product_Stats::get_post_type_breakdown(),
		);
	}

	/**
	 * Force-delete the {@see Singleton_Template_Cpt} customization for the
	 * requested post type, backing the dashboard's "Restore default" link.
	 * `before_delete_post` in the base class clears the option pointer +
	 * per-request cache so the next render falls back to the bundled template.
	 *
	 * DELETE `jetpack/v4/search/templates/<post_type>`
	 *
	 * @param WP_REST_Request $request - REST request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function reset_singleton_template( $request ) {
		$cpt_class = $this->resolve_singleton_template_class( $request['post_type'] );
		if ( ! $cpt_class ) {
			return new WP_Error(
				'jetpack_search_template_unknown',
				__( 'Unknown search template.', 'jetpack-search-pkg' ),
				array( 'status' => 404 )
			);
		}
		if ( ! $cpt_class::is_customized() ) {
			return new WP_Error(
				'jetpack_search_template_not_customized',
				__( 'No customization to restore.', 'jetpack-search-pkg' ),
				array( 'status' => 404 )
			);
		}
		$post_id = $cpt_class::get_post_id();
		if ( ! wp_delete_post( $post_id, true ) ) {
			return new WP_Error(
				'jetpack_search_template_reset_failed',
				__( 'Failed to restore the default template.', 'jetpack-search-pkg' ),
				array( 'status' => 500 )
			);
		}
		return rest_ensure_response( array( 'deleted' => true ) );
	}

	/**
	 * Map a CPT slug to its concrete `Singleton_Template_Cpt` subclass.
	 * Returns null when the slug isn't one of the registered singleton-template
	 * CPTs — the route only sanitizes the slug (via `sanitize_key`), so this
	 * lookup is the primary "is this a known CPT?" filter, not a backup check.
	 *
	 * @param string $post_type Post type slug from the request.
	 * @return class-string<Singleton_Template_Cpt>|null
	 */
	protected function resolve_singleton_template_class( $post_type ) {
		$map = array(
			Overlay_Template::POST_TYPE         => Overlay_Template::class,
			Product_Overlay_Template::POST_TYPE => Product_Overlay_Template::class,
			Search_Template::POST_TYPE          => Search_Template::class,
			Product_Search_Template::POST_TYPE  => Product_Search_Template::class,
		);
		return $map[ $post_type ] ?? null;
	}

	/**
	 * Pricing for record count of the site
	 */
	public function product_pricing() {
		$tier_pricing = Search_Product::get_pricing_for_ui();
		// we can force the plugin to use the new pricing by appending `new_pricing_202208=1` to URL.
		if ( Helper::is_forced_new_pricing_202208() ) {
			$tier_pricing['pricing_version'] = Plan::JETPACK_SEARCH_NEW_PRICING_VERSION;
		}
		return rest_ensure_response( $tier_pricing );
	}

	/**
	 * Forward remote response to client with error handling.
	 *
	 * @param array|WP_Error $response - Response from WPCOM.
	 */
	protected function make_proper_response( $response ) {
		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$body        = json_decode( wp_remote_retrieve_body( $response ), true );
		$status_code = wp_remote_retrieve_response_code( $response );

		if ( 200 === $status_code ) {
			return $body;
		}

		return new WP_Error(
			isset( $body['error'] ) ? 'remote-error-' . $body['error'] : 'remote-error',
			$body['message'] ?? 'unknown remote error',
			array( 'status' => $status_code )
		);
	}

	/**
	 * Get blog id
	 */
	protected function get_blog_id() {
		return $this->is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
	}
}
