<?php

namespace Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Webhook;

use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Telegram_Endpoint;
use Limb_Chatbot\Includes\Integrations\Telegram\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Integrations\Telegram\Utilities\Webhook_Utility;

/**
 * Telegram Webhook Endpoint
 *
 * Handles webhook operations with the Telegram API including:
 * - Setting webhook (setWebhook)
 * - Deleting webhook (deleteWebhook)
 * - Getting webhook info (getWebhookInfo)
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Webhook
 * @since 1.0.11
 */
class Webhook_Endpoint extends Telegram_Endpoint {

	/**
	 * Webhook_Endpoint constructor.
	 *
	 * @param Webhook_Utility $utility Utility object containing configuration and context.
	 *
	 * @since 1.0.11
	 */
	public function __construct( Webhook_Utility $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Set webhook for the bot.
	 *
	 * @param string $url          Webhook URL.
	 * @param string $secret_token Secret token for verification.
	 *
	 * @return array Response from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function set_webhook( string $url, string $secret_token = '' ): array {
		$http_client = $this->http_client_factory();
		$api_url     = $this->build_url( 'setWebhook' );

		$body = [
			'url'             => $url,
			'allowed_updates' => [ 'message', 'my_chat_member' ],
		];

		if ( ! empty( $secret_token ) ) {
			$body['secret_token'] = $secret_token;
		}

		$response = $http_client->post(
			$api_url,
			[
				'body'    => wp_json_encode( $body ),
				'headers' => [
					'Content-Type' => 'application/json',
				],
			]
		);

		$handler = new Response_Handler( $response, $http_client, $this );
		$result  = $handler->get_body();

		if ( empty( $result['ok'] ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				$result['description'] ?? __( 'Failed to set Telegram webhook.', 'limb-chatbot' ),
				$result,
				400
			);
		}

		return $result;
	}

	/**
	 * Delete webhook for the bot.
	 *
	 * @param bool $drop_pending_updates Whether to drop pending updates.
	 *
	 * @return array Response from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function delete_webhook( bool $drop_pending_updates = false ): array {
		$http_client = $this->http_client_factory();
		$api_url     = $this->build_url( 'deleteWebhook' );

		$body = [];
		if ( $drop_pending_updates ) {
			$body['drop_pending_updates'] = true;
		}

		$response = $http_client->post(
			$api_url,
			[
				'body'    => wp_json_encode( $body ),
				'headers' => [
					'Content-Type' => 'application/json',
				],
			]
		);

		$handler = new Response_Handler( $response, $http_client, $this );
		$result  = $handler->get_body();

		if ( empty( $result['ok'] ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				$result['description'] ?? __( 'Failed to delete Telegram webhook.', 'limb-chatbot' ),
				$result,
				400
			);
		}

		return $result;
	}

	/**
	 * Get current webhook info.
	 *
	 * @return array Webhook info from Telegram API.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function get_webhook_info(): array {
		$http_client = $this->http_client_factory();
		$api_url     = $this->build_url( 'getWebhookInfo' );

		$response = $http_client->get( $api_url );

		$handler = new Response_Handler( $response, $http_client, $this );
		$result  = $handler->get_body();

		if ( empty( $result['ok'] ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				$result['description'] ?? __( 'Failed to get Telegram webhook info.', 'limb-chatbot' ),
				$result,
				400
			);
		}

		return $result['result'] ?? [];
	}
}
