<?php

namespace Limb_Chatbot\Includes\Vector_Dbs\Pinecone;

use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Services\Helper;
use Limb_Chatbot\Includes\Services\Response_Handler as Base_Response_Handler;
use Limb_Chatbot\Includes\Interfaces\Response_Handler_Interface;


/**
 * Class Response_Handler
 *
 * Handles responses from Pinecone vector DB API.
 *
 * @since 1.0.0
 */
class Response_Handler extends Base_Response_Handler implements Response_Handler_Interface {

	/**
	 * Cast response body as associative array.
	 *
	 * @var bool|null
	 * @since 1.0.0
	 */
	protected ?bool $body_cast_array = true;

	/**
	 * Parse the response and check for errors.
	 *
	 * @return void
	 *
	 * @throws Exception If response contains an error.
	 *
	 * @since 1.0.0
	 */
	public function parse() {
		static::check_for_errors();
		parent::parse();
	}

	/**
	 * Checks if response status indicates error and throws exception accordingly.
	 *
	 * @return void
	 *
	 * @throws Exception On Pinecone API errors.
	 *
	 * @since 1.0.0
	 */
	protected function check_for_errors(): void {
		if ( ! $this->status_starts_with_2() ) {
			if ( ! empty( $this->get_body()['error'] ) ) {
				throw new Exception( Error_Codes::PINECONE_ERROR, $this->get_body()['error']['message'] ?? Pinecone::$id . ' error', $this->get_body()['error'] );
			} elseif ( ! empty( $this->get_body()['message'] ) ) {
				throw new Exception( Error_Codes::PINECONE_ERROR, $this->get_body()['message'] ?? Pinecone::$id . ' error', $this->get_body() );
			} else {
				throw new Exception( Error_Codes::PINECONE_ERROR, Pinecone::$id . ' error', $this->get_body() );
			}
		}
	}

	/**
	 * Defines and parses the response body.
	 *
	 * @return void
	 *
	 * @since 1.0.0
	 */
	public function define_body(): void {
		$body = wp_remote_retrieve_body( $this->response );
		if ( $this->is_application_json() || Helper::is_probable_json( $body ) ) {
			$body = json_decode( $body, $this->body_cast_array );
		}
		$this->body = $body;
	}
}
