<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints;

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

	/**
	 * OpenRouter API base URL.
	 *
	 * @var string
	 * @since 1.0.14
	 */
	const API_BASE_URL = 'https://openrouter.ai/api/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  $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.14
	 */
	protected function get_header( ?Config $config = null, 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_Router::$id, 'api-keys' ) );
		}

		return array(
			'Authorization' => 'Bearer ' . $config->get_params()['api_key'],
			'Content-Type'  => $content_type,
			'HTTP-Referer'  => get_site_url(),
		);
	}

	/**
	 * Get public headers for endpoints that don't require authentication.
	 *
	 * @return array Headers array.
	 * @since 1.0.14
	 */
	public function get_public_header(): array {
		$headers = [
			'Content-Type'  => 'application/json',
		];

		// Include API key if available for better rate limits
		$config = $this->get_config();
		if ( $config && ! empty( $config->get_params()['api_key'] ) ) {
			$headers['Authorization'] = 'Bearer ' . $config->get_params()['api_key'];
		}

		return $headers;
	}
}
