<?php

namespace Limb_Chatbot\Includes\Services\Actions;

use Exception;
use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Data_Objects\Message;
use Limb_Chatbot\Includes\Data_Objects\Parameter;
use Limb_Chatbot\Includes\Interfaces\Parameter_Callback_Handler_Interface;
use Limb_Chatbot\Includes\Services\Helper;
use Limb_Chatbot\Includes\Utilities\Chatbot_Utility;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Handler for vector search parameter callbacks.
 *
 * Implements the Parameter_Callback_Handler_Interface to handle
 * vector search requests for parameters with TYPE_VECTOR_SEARCH.
 *
 * Follows SOLID principles:
 * - Single Responsibility: Handles only vector search logic
 * - Open/Closed: Extensible through interface implementation
 * - Liskov Substitution: Implements handler interface contract
 * - Interface Segregation: Depends only on necessary interface
 * - Dependency Inversion: Uses abstractions (interfaces)
 *
 * @since 1.0.0
 */
class Vector_Search_Handler implements Parameter_Callback_Handler_Interface {

	/**
	 * Handle vector search parameter callback.
	 *
	 * Processes the incoming request with chat context and performs
	 * vector search using the provided search keyword.
	 *
	 * @param  WP_REST_Request  $request  The incoming REST request.
	 *
	 * @return WP_REST_Response The response to return to the client.
	 *
	 * @since 1.0.0
	 */
	public function handle( WP_REST_Request $request ): WP_REST_Response {
		// Get parameter from request
		$parameter = $request->get_param( '_parameter' );
		if ( ! $parameter instanceof Parameter ) {
			throw new Exception( __( 'Invalid parameter instance', 'limb-chatbot' ) );
		}

		// Get chat from request
		$chat = $request->get_param( '_chat' );
		if ( ! $chat instanceof Chat ) {
			throw new Exception( __( 'Invalid chat instance', 'limb-chatbot' ) );
		}

		// Get search keyword
		$search_keyword = $request->get_param( 'search_keyword' ) ?? '';

		// Get chatbot and build utility
		$chatbot = $chat->get_chatbot();
		if ( ! $chatbot ) {
			throw new Exception( __( 'Chatbot not found', 'limb-chatbot' ) );
		}

		$ai_model = $chatbot->get_ai_model();
		if ( ! $ai_model ) {
			throw new Exception( __( 'AI model not configured', 'limb-chatbot' ) );
		}

		// Build chatbot utility
		$chatbot_utility = new Chatbot_Utility( $chatbot );
		$chatbot_utility->set_chat( $chat );

		// Create search query message
		$search_query = Message::make( array(
			'content'   => array(
				array(
					'type' => 'text',
					'text' => array(
						'value' => sanitize_text_field( $search_keyword ),
					),
				),
			),
			'role'      => Message::ROLE_USER,
			'chat_uuid' => $chat->get_uuid(),
		) );

		// Perform search
		$search_provider = new Search_Results_Provider( $chatbot_utility );
		$results         = $search_provider->get_results( $parameter, $search_query );

		// Format response
		$response_data = array(
			'status'       => 'success',
			'parameter_id' => $parameter->get_id(),
			'chat_uuid'    => $chat->get_uuid(),
			'search_query' => sanitize_text_field( $search_keyword ),
			'results'      => array(),
		);

		if ( ! empty( $results['results'] ) ) {
			$response_data['results'] = $results['results'];
			$response_data['count']   = count( $results['results'] );
		} else {
			$response_data['count']   = 0;
			$response_data['message'] = __( 'No results found', 'limb-chatbot' );
		}

		return rest_ensure_response( $response_data );
	}
}

