<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Open_Ai;
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 Open_Ai_Endpoint
 *
 * Base endpoint class for OpenAI API interactions.
 * Provides common functionality such as header generation including authentication.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints
 * @since 1.0.0
 */
class Open_Ai_Endpoint extends Endpoint {

	/**
	 * OpenAI API base URL.
	 *
	 * @var string
	 * @since 1.0.0
	 */
	const API_BASE_URL = 'https://api.openai.com/v1';

	/**
	 * Generate HTTP headers for API requests.
	 *
	 * Throws exception if API key is missing or empty.
	 *
	 * @param  Config|null  $config  Optional Config object. If null, uses internal config.
	 * @param  string  $beta_version  Optional beta version string to be sent in 'OpenAI-Beta' header.
	 * @param  string  $content_type  Content-Type header value. Defaults to 'application/json'.
	 *
	 * @return array<string, string> HTTP headers including Authorization.
	 *
	 * @throws Exception Throws if API key is missing or empty in the config.
	 *
	 * @since 1.0.0
	 */
	protected function get_header( ?Config $config = null, string $beta_version = '', string $content_type = 'application/json' ): array {
		$config = $config ?? $this->get_config();
		if ( ! ( $config instanceof Config ) ) {
			throw ( new Exception( Error_Codes::AUTHENTICATION_API_KEY_MISSING, __( 'Api key is missing.', 'limb-chatbot' ) ) )->with_link( $this->utility, null, null, null, 'ai-settings', 'config_id' );
		}
		if ( empty( $config->get_params()['api_key'] ) ) {
			throw ( ( new Exception( Error_Codes::AUTHENTICATION_API_KEY_MISSING, __( 'Api key is empty.', 'limb-chatbot' ) ) )->with_link( $this->utility, null, null, Open_Ai::$id, 'api-keys' ) );
		}
		$header = array(
			'Authorization' => 'Bearer ' . $config->get_params()['api_key'],
			'Content-Type'  => $content_type
		);
		if ( $beta_version ) {
			$header['OpenAI-Beta'] = $beta_version;
		}

		return $header;
	}
}