<?php
/**
 * REST endpoints for maca Hub (maca-hub/v1 namespace, site key auth).
 *
 * @package Maca_Tjatt
 */

defined( 'ABSPATH' ) || exit;

/**
 * Hub REST controller.
 */
class Maca_Tjatt_Hub_Rest {

	/**
	 * @return void
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * @return void
	 */
	public function register_routes() {
		$key_args = array(
			'maca_key' => array(
				'required'          => false,
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			),
		);

		register_rest_route(
			'maca-hub/v1',
			'/tjatt',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_status' ),
				'permission_callback' => array( $this, 'check_site_key' ),
				'args'                => $key_args,
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/tjatt/update',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_settings' ),
				'permission_callback' => array( $this, 'check_site_key' ),
				'args'                => $key_args,
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/tjatt/build-index',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'build_index' ),
				'permission_callback' => array( $this, 'check_site_key' ),
				'args'                => $key_args,
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return true|WP_Error
	 */
	public function check_site_key( $request ) {
		if ( class_exists( 'Maca_Hub_Connector' ) && Maca_Hub_Connector::request_has_valid_bearer( $request ) ) {
			return true;
		}

		$stored = maca_tjatt_hub_get_site_key();
		if ( '' === $stored ) {
			return new WP_Error(
				'maca_no_site_key',
				__( 'No site key stored in WordPress (maca Sec Hub).', 'maca-tjatt' ),
				array( 'status' => 401 )
			);
		}

		$key = $this->extract_request_site_key( $request );
		if ( '' === $key ) {
			return new WP_Error(
				'maca_missing_key',
				__( 'Site key is missing.', 'maca-tjatt' ),
				array( 'status' => 401 )
			);
		}

		if ( ! hash_equals( $stored, $key ) ) {
			return new WP_Error(
				'maca_invalid_key',
				__( 'Invalid site key.', 'maca-tjatt' ),
				array( 'status' => 401 )
			);
		}

		return true;
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return string
	 */
	private function extract_request_site_key( $request ) {
		$key = $request->get_header( 'X-Maca-Site-Key' );
		if ( is_string( $key ) && '' !== trim( $key ) ) {
			return trim( $key );
		}

		$key = $request->get_param( 'maca_key' );
		if ( is_string( $key ) && '' !== trim( $key ) ) {
			return trim( $key );
		}

		return '';
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_status() {
		return rest_ensure_response( maca_tjatt_hub_get_status() );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_settings( WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			return new WP_Error(
				'maca_tjatt_invalid_body',
				__( 'Invalid request body.', 'maca-tjatt' ),
				array( 'status' => 400 )
			);
		}

		$patch = array();
		$map   = array(
			'enabled',
			'floating',
			'name',
			'rate_limit',
			'index_all_pages',
			'index_posts',
			'chat_model',
			'custom_knowledge',
		);

		foreach ( $map as $key ) {
			if ( array_key_exists( $key, $body ) ) {
				if ( in_array( $key, array( 'enabled', 'floating', 'index_all_pages', 'index_posts' ), true ) ) {
					$patch[ $key ] = $this->request_bool( $body[ $key ] );
				} else {
					$patch[ $key ] = $body[ $key ];
				}
			}
		}

		$result = maca_tjatt_hub_update_settings( $patch );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function build_index() {
		$result = maca_tjatt_hub_build_index();
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * Parse booleans from Hub requests without treating "false" as true.
	 *
	 * @param mixed $value Request value.
	 * @return bool
	 */
	private function request_bool( $value ) {
		if ( is_bool( $value ) ) {
			return $value;
		}
		if ( is_int( $value ) || is_float( $value ) ) {
			return 0 !== (int) $value;
		}
		if ( is_string( $value ) ) {
			return in_array( strtolower( trim( $value ) ), array( '1', 'true', 'yes', 'on' ), true );
		}
		return ! empty( $value );
	}
}
