<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Model\Handlers\Model_Response_Handler;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Utilities\AI_Model_Utility;
use Limb_Chatbot\Includes\Data_Objects\AI_Model;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Model_Endpoint
 *
 * Handles API requests related to AI models such as deleting, retrieving, and listing models.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints
 * @since 1.0.0
 */
class Model_Endpoint extends Open_Ai_Endpoint {

	/**
	 * Constructor.
	 *
	 * @param AI_Model_Utility $utility Utility class instance used for configuration and helper methods.
	 * @since 1.0.0
	 */
	public function __construct( AI_Model_Utility $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Deletes a specified AI model via the API.
	 *
	 * @param  AI_Model  $model  The AI model to delete.
	 *
	 * @return bool True if deletion was successful, false otherwise.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function delete( AI_Model $model ) {
		$http_client = $this->http_client_factory();
		$response    = $http_client->request( self::API_BASE_URL . '/models/' . $model->get_name(), array(
			'method'  => 'DELETE',
			'headers' => $this->get_header(),
			'timeout' => $this->utility->get_timeout(),
		) );

		return ( new Model_Response_Handler( $response, $http_client, $this ) )->is_deleted();
	}

	/**
	 * Retrieves information about a specified AI model.
	 *
	 * @param  AI_Model  $model  The AI model to retrieve.
	 *
	 * @return AI_Model|null The retrieved AI model data or null if not found.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function retrieve( AI_Model $model ) {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get( self::API_BASE_URL . '/models/' . $model->get_name(), array(
			'headers' => $this->get_header(),
			'timeout' => $this->utility->get_timeout(),
		) );

		return ( new Model_Response_Handler( $response, $http_client, $this ) )->get_model();
	}

	/**
	 * Lists all available AI models from the API.
	 *
	 * @return AI_Model[] List of AI models.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function list() {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get( self::API_BASE_URL . '/models', array(
			'headers' => $this->get_header(),
			'timeout' => $this->utility->get_timeout(),
		) );

		return (array) ( new Model_Response_Handler( $response, $http_client, $this ) )->get_body();
	}
}