<?php

namespace Limb_Chatbot\Includes\Repositories;

use Limb_Chatbot\Includes\Data_Objects\AI_Model;
use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\Data_Objects\Vector_Index_Vector;
use Limb_Chatbot\Includes\Services\Collection;

/**
 * Repository for managing Vector data objects.
 *
 * @since 1.0.0
 */
class Vector_Repository {

	/**
	 * Retrieves vectors based on given parameters.
	 *
	 * Supports pagination, sorting, and eager loading of relations.
	 *
	 * @param  array  $params  Query parameters including 'per_page', 'page', 'orderby', 'order', 'include', and 'meta_keys'.
	 *
	 * @return Collection Collection of Vector objects.
	 * @since 1.0.0
	 *
	 */
	public function get_items( array $params ): Collection {
		$vectors = Vector::where( $params, $params['per_page'] ?? 10, $params['page'] ?? 1, $params['orderby'] ?? 'id', $params['order'] ?? 'DESC' );
		if ( ! $vectors->is_empty() && ! empty( $params['include'] ) && $include = $params['include'] ) {
			foreach ( $include as $relation ) {
				$args    = $relation === 'metas' && ! empty( $params['meta_keys'] ) ? [ 'meta_key' => $params['meta_keys'] ] : [];
				$vectors = $vectors->with( $relation, $args );
			}
		}

		return $vectors;
	}

	/**
	 * Retrieves a Vector linked to a given Vector Index ID.
	 *
	 * @param  int  $vector_index_id  The ID of the vector index.
	 *
	 * @return Vector|null The linked Vector or null if not found.
	 * @since 1.0.0
	 */
	public function get_index_vector( int $vector_index_id, $ai_model_id = null, $dimension = null ): ?Vector {
		$vector_index_vector = Vector_Index_Vector::where( [ 'vector_index_id' => $vector_index_id ] )->pluck( 'vector_id' );
		$where               = [ 'id' => $vector_index_vector ];
		if ( ! empty( $ai_model_id ) ) {
			$where['ai_model_id'] = $ai_model_id;
		}
		if ( ! empty( $dimension ) ) {
			$where['dimension'] = $dimension;
		}

		return Vector::where( $where, 1, 1 )->first();
	}
}