<?php

namespace Limb_Chatbot\Includes\Integrations\Telegram\Endpoints;

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

/**
 * Base Telegram Endpoint
 *
 * Provides common functionality for Telegram API interactions including
 * authentication and base URL management.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Endpoints
 * @since 1.0.11
 */
class Telegram_Endpoint extends Endpoint {

	/**
	 * Telegram API base URL.
	 *
	 * @var string
	 * @since 1.0.11
	 */
	const API_BASE_URL = 'https://api.telegram.org';

	/**
	 * Get bot token from config.
	 *
	 * @param Config|null $config Optional Config object. If null, uses internal config.
	 *
	 * @return string Bot token.
	 * @throws Exception If bot token is missing or empty.
	 * @since 1.0.11
	 */
	protected function get_bot_token( ?Config $config = null ): string {
		$config = $config ?? $this->get_config();
		if ( ! ( $config instanceof Config ) ) {
			throw new Exception(
				Error_Codes::AUTHENTICATION_API_KEY_MISSING,
				__( 'Telegram configuration is missing.', 'limb-chatbot' ),
				null,
				400
			);
		}

		$params = $config->get_params();

		if ( empty( $params['bot_token'] ) ) {
			throw new Exception(
				Error_Codes::AUTHENTICATION_API_KEY_MISSING,
				__( 'Telegram bot token is missing or empty.', 'limb-chatbot' ),
				null,
				400
			);
		}

		return $params['bot_token'];
	}

	/**
	 * Build API URL with bot token.
	 *
	 * @param string $method Telegram API method name.
	 *
	 * @return string Full API URL.
	 * @throws Exception If bot token is missing.
	 * @since 1.0.11
	 */
	protected function build_url( string $method ): string {
		$token = $this->get_bot_token();

		$url = self::API_BASE_URL . '/bot' . $token . '/' . $method;

		return $url;
	}

	/**
	 * Get configuration object from utility.
	 *
	 * @return Config|null
	 * @since 1.0.11
	 */
	public function get_config(): ?Config {
		return $this->utility->config ?? null;
	}
}

