<?php

namespace Limb_Chatbot\Includes\Services\Actions\Recommendation_Search_Processors;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\Vector_Index;
use Limb_Chatbot\Includes\Interfaces\Recommendation_Search_Processor_Interface;
use Limb_Chatbot\Includes\Services\Collection;
use Limb_Chatbot\Includes\Utilities\Chatbot_Utility;
use WP_Query;

class WP_Search_Processor implements Recommendation_Search_Processor_Interface {

	public function search( Chatbot_Utility $utility, $search_query, $vector_index, $similarity_score ): ?array {
		$datasets = $this->get_datasets( $vector_index );
		if ( empty( $datasets ) ) {
			return $datasets;
		}
		$post_type         = $datasets->first()->get_source_sub_type();
		$ids               = $datasets->pluck( 'source' );
		$search_query_text = trim( $search_query->extract_text() );

		$args = [
			'post_type'      => $post_type,
			'post__in'       => $ids,
			'posts_per_page' => - 1,
			'post_status'    => 'publish',
			'orderby'        => 'post__in',
		];

		if ( ! empty( $search_query_text ) ) {
			$args['s'] = $search_query_text;
		}

		$query   = new WP_Query( $args );
		$posts   = $query->posts;
		$results = [];
		if ( ! empty( $posts ) ) {
			foreach ( $posts as $post ) {
				if ( ! $post instanceof \WP_Post ) {
					continue;
				}
				$dataset = $datasets->filter( function ( Dataset $dataset ) use ( $post ) {
					return $dataset->source == $post->ID;
				} )->first();
				if ( $dataset instanceof Dataset ) {
					$results[] = $dataset->dataset_entries()[0];
				}
			}
		}

		return $results;
	}

	private function get_datasets( Vector_Index $vector_index ) {
		$datasets = $vector_index->get_datasets();
		if ( ! $datasets instanceof Collection || $datasets->is_empty() ) {
			return [];
		}

		return $datasets;
	}
}