<?php

namespace Limb_Chatbot\Includes\Vector_Dbs\Pinecone\Endpoints\Index;

use Limb_Chatbot\Includes\Data_Objects\Vector_Index_Meta;
use Limb_Chatbot\Includes\Services\Collection;
use Limb_Chatbot\Includes\Vector_Dbs\Pinecone\Response_Handler as Base_Response_Handler;

/**
 * Class Response_Handler
 *
 * Handles the response from Pinecone Index API calls,
 * parsing and extracting metadata about the index.
 *
 * @package Limb_Chatbot\Includes\Vector_Dbs\Pinecone\Endpoints\Index
 *
 * @since 1.0.0
 */
class Response_Handler extends Base_Response_Handler {

	/**
	 * Collection of Vector_Index_Meta objects extracted from response
	 *
	 * @var Collection|null
	 */
	protected ?Collection $metas = null;

	/**
	 * Whether the response body should be cast to array
	 *
	 * @var bool|null
	 */
	protected ?bool $body_cast_array = true;

	/**
	 * Parse the response and extract metadata if no error is present.
	 *
	 * @return void
	 *
	 * @since 1.0.0
	 */
	public function parse() {
		parent::parse();
		if ( ! $this->has_error() ) {
			$this->define_metas();
		}
	}

	/**
	 * Get the collection of metadata extracted from the response.
	 *
	 * @return Collection|null Collection of Vector_Index_Meta objects or null if not parsed yet.
	 *
	 * @since 1.0.0
	 */
	public function get_metas(): ?Collection {
		return $this->metas;
	}

	/**
	 * Define metadata collection by extracting relevant fields from response body.
	 *
	 * @return void
	 *
	 * @since 1.0.0
	 */
	protected function define_metas(): void {
		$this->metas = new Collection();
		$this->metas->push_item( Vector_Index_Meta::make( [ 'meta_key' => 'host', 'meta_value' => $this->get_body()['host'] ] ) );
		$this->metas->push_item( Vector_Index_Meta::make( [ 'meta_key' => 'status', 'meta_value' => $this->get_body()['status']['state'] ] ) );
	}
}
