<?php

namespace Limb_Chatbot\Includes\Services\Actions\Parameter_Types;

use Limb_Chatbot\Includes\Data_Objects\Parameter;

/**
 * Class Vector_Search_Parameter_Type
 *
 * Handles vector search parameter validation and sanitization.
 * Validates that the value is a valid post ID from search results.
 *
 * @package Limb_Chatbot\Includes\Services\Actions\Parameter_Types
 * @since 1.0.0
 */
class Vector_Search_Parameter_Type extends Abstract_Parameter_Type {

	/**
	 * @inheritDoc
	 */
	public function get_type(): string {
		return Parameter::TYPE_VECTOR_SEARCH;
	}

	/**
	 * @inheritDoc
	 */
	public function sanitize( string $value, Parameter $parameter ): string {
		// Ensure value is a valid post ID (numeric)
		$post_id = (int) $value;
		return (string) $post_id;
	}

	/**
	 * @inheritDoc
	 */
	public function validate( string $value, Parameter $parameter ): bool {
		$this->clear_errors();

		$trimmed_value = trim( $value );

		// Check if field is empty
		if ( empty( $trimmed_value ) ) {
			// If empty and required, show required error
			if ( $this->is_required( $parameter ) ) {
				$this->add_error( sprintf( __( '%s is required.', 'limb-chatbot' ), $this->get_label( $parameter ) ) );
				return false;
			}
			// If empty and not required, it's valid
			return true;
		}
		// Validate that value is numeric (post ID)
		if ( ! is_numeric( $trimmed_value ) ) {
			$this->add_error( sprintf( __( '%s must be a valid post.', 'limb-chatbot' ), $this->get_label( $parameter ) ) );
			return false;
		}

		$post_id = (int) $trimmed_value;

		// Validate that post exists
		if ( $post_id <= 0 || ! ( $post = get_post( $post_id ) ) ) {
			$this->add_error( sprintf( __( 'The selected %s does not exist.', 'limb-chatbot' ), strtolower( $this->get_label( $parameter ) ) ) );
			return false;
		}

		return true;
	}

	/**
	 * @inheritDoc
	 */
	public function get_hint( Parameter $parameter ): ?string {
		return sprintf(
			__( 'Search and choose from corresponding results', 'limb-chatbot' ),
			$this->get_label( $parameter )
		);
	}

	public function get_config_schema(): array {
		return array(
			'cpt' => array(
				'type'        => 'string',
				'description' => 'CPT Name',
				'required'    => true,
			),
			'similarity_score' => array(
				'type'        => 'integer',
				'description' => 'The similarity score',
				'default'     => 45,
				'required'    => false,
			),
			'lead_capture_map_field' => array(
				'type'        => 'integer',
				'description' => 'Lead capture map field',
				'required'    => false,
			),
		);
	}
}

