<?php

namespace Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Gemini\Services\Google_OAuth_Service;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Services\Endpoint;
use Limb_Chatbot\Includes\Data_Objects\Config;


/**
 * Class Gemini_Endpoint
 *
 * Base endpoint class for Gemini API requests.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints
 * @since 1.0.0
 */
class Gemini_Endpoint extends Endpoint {
	/**
	 * Base URL for Gemini API.
	 *
	 * @var string
	 */
	const API_BASE_URL = 'https://generativelanguage.googleapis.com/';

	/**
	 * AI provider reference (optional).
	 *
	 * @var mixed
	 */
	public $ai_provider;

	/**
	 * Generate request headers for Gemini API.
	 *
	 * @param  bool  $include_token  Whether to include the OAuth token.
	 *
	 * @return array Associative array of headers.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function get_header( bool $include_token = false ) {
		$headers = array(
			'Content-Type' => 'application/json',
		);
		if ( $include_token ) {
			$google_oauth             = new Google_OAuth_Service();
			$headers['Authorization'] = 'Bearer ' . $google_oauth->get_oauth_token();
		}

		return $headers;
	}

	/**
	 * Get the API key from config object or utility.
	 *
	 * @param Config|null $config Optional config object.
	 *
	 * @return string The API key string.
	 * @throws Exception If API key is missing or config is invalid.
	 * @since 1.0.0
	 */
	public function get_auth_key( ?Config $config = null ): string {
		$config = $config ?? $this->get_config();
		if ( empty( $config ) || ! ( $config instanceof Config ) || empty( $config->get_params()['api_key'] ) ) {
			throw ( new Exception( Error_Codes::AUTHENTICATION_API_KEY_MISSING, __( 'Api key is missing', 'limb-chatbot' ) ) )->attach_utility( $this->get_utility() );
		}

		return $config->get_params()['api_key'];
	}

}