<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Key;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Key_Response_Handler
 *
 * Handles parsing of OpenRouter /key API responses.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Key
 * @since 1.0.14
 */
class Key_Response_Handler extends Response_Handler {

	/**
	 * Retrieves the API key information from the response.
	 *
	 * @return object The API key data object.
	 * @throws Exception If response parsing fails.
	 * @since 1.0.14
	 */
	public function get_key_info(): object {
		$body = $this->get_body();

		if ( empty( $body->data ) ) {
			return (object) [];
		}

		return $body->data;
	}

	/**
	 * Checks if the API key is a free tier key.
	 *
	 * @return bool True if free tier.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function is_free_tier(): bool {
		$key_info = $this->get_key_info();

		return $key_info->is_free_tier ?? false;
	}

	/**
	 * Gets the API key usage in USD.
	 *
	 * @return float Usage amount.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function get_usage(): float {
		$key_info = $this->get_key_info();

		return (float) ( $key_info->usage ?? 0 );
	}

	/**
	 * Gets the API key limit in USD.
	 *
	 * @return float|null Limit amount or null if unlimited.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function get_limit(): ?float {
		$key_info = $this->get_key_info();

		return $key_info->limit ?? null;
	}

	/**
	 * Gets the remaining limit in USD.
	 *
	 * @return float|null Remaining limit or null if unlimited.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function get_limit_remaining(): ?float {
		$key_info = $this->get_key_info();

		return $key_info->limit_remaining ?? null;
	}
}
