<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Key\Key_Response_Handler;
use Limb_Chatbot\Includes\AI_Providers\Open_Router\Utilities\Key_Utility;
use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Key_Endpoint
 *
 * Handles API requests to validate API keys via OpenRouter's /key endpoint.
 *
 * Endpoint: GET https://openrouter.ai/api/v1/key
 *
 * This endpoint requires authentication and returns information about the API key,
 * making it ideal for validating API credentials.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints
 * @since 1.0.14
 */
class Key_Endpoint extends Open_Router_Endpoint {

	/**
	 * Key_Endpoint constructor.
	 *
	 * @param Config $config Configuration object with API key.
	 * @since 1.0.14
	 */
	public function __construct( Config $config ) {
		parent::__construct( new Key_Utility( $config ) );
	}

	/**
	 * Retrieves information about the current API key.
	 *
	 * Makes a GET request to /key endpoint to validate the API key
	 * and retrieve key information (usage, limits, etc.).
	 *
	 * @return object The API key information.
	 * @throws Exception If authentication fails or other API errors occur.
	 * @since 1.0.14
	 */
	public function get(): object {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get( self::API_BASE_URL . '/key', [
			'headers' => $this->get_header(),
			'timeout' => $this->utility->get_timeout(),
		] );

		return ( new Key_Response_Handler( $response, $http_client, $this ) )->get_key_info();
	}

	/**
	 * Validates the API key by attempting to retrieve key information.
	 *
	 * @return bool True if the API key is valid.
	 * @throws Exception If authentication fails.
	 * @since 1.0.14
	 */
	public function validate(): bool {
		$key_info = $this->get();

		return ! empty( $key_info );
	}
}
