<?php

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

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\Utilities\Messages_Utility;
use Limb_Chatbot\Includes\Integrations\Telegram\Utilities\Users_Utility;

/**
 * Telegram Users Endpoint
 *
 * Handles user-related operations with the Telegram API including:
 * - Fetching updates to find private chats with users
 * - Retrieving single user/chat info
 *
 * Private chats are identified by type="private" in the chat object.
 * User data includes: id, first_name, last_name, username, language_code.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Users
 * @since 1.0.11
 */
class Users_Endpoint extends Telegram_Endpoint {

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

	/**
	 * List private chat users from Telegram bot updates.
	 *
	 * Fetches updates using getUpdates and filters for private chat messages
	 * to find users who have interacted with the bot.
	 *
	 * @return array Array of user objects with Telegram user data.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function list(): array {
		$http_client = $this->http_client_factory();
		$url         = $this->build_url( 'getUpdates' );

		$response = $http_client->get(
			$url,
			[
				'timeout'   => $this->utility->get_timeout(),
			]
		);

		// Handle WP_Error
		if ( is_wp_error( $response ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				$response->get_error_message(),
				null,
				400
			);
		}

		$handler = new Users_Response_Handler( $response, $http_client, $this );

		return $handler->get_users();
	}

 	/**
	 * List private chat users with profile photos.
	 *
	 * Fetches updates and enriches user data with profile photo URLs.
	 *
	 * @return array Array of user objects with profile_photo_url field.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function list_with_photos(): array {
		$users = $this->list();

		return $this->enrich_users_with_photos( $users );
	}

	/**
	 * Enrich user data with profile photos.
	 *
	 * @param array $users Array of user objects.
	 *
	 * @return array Users with profile_photo_url added.
	 * @since 1.0.11
	 */
	private function enrich_users_with_photos( array $users ): array {
		if ( empty( $users ) ) {
			return $users;
		}

		// Use Messages_Endpoint to fetch photos
		$messages_utility = new Messages_Utility(
			$this->get_config()
		);

		foreach ( $users as &$user ) {
			$user_id = $user['id'] ?? null;
			if ( $user_id ) {
				try {
					$user['profile_photo_url'] = $messages_utility->get_user_avatar_url( (int) $user_id );
				} catch ( \Exception $e ) {
					$user['profile_photo_url'] = null;
				}
			} else {
				$user['profile_photo_url'] = null;
			}
		}

		return $users;
	}

	/**
	 * Retrieve a single user/chat by ID.
	 *
	 * Uses getChat to retrieve chat info for a private chat.
	 *
	 * @return array Chat object with user details.
	 * @throws Exception
	 * @since 1.0.11
	 */
	public function retrieve(): array {
		$http_client = $this->http_client_factory();
		$url         = $this->build_url( 'getChat' ) . '?' . http_build_query( [
			'chat_id' => $this->utility->chat_id,
		] );

		$response = $http_client->get(
			$url,
			[
				'timeout'   => $this->utility->get_timeout(),
			]
		);

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

		if ( empty( $result['ok'] ) || ! isset( $result['result'] ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				__( 'Failed to fetch Telegram user.', 'limb-chatbot' ),
				$result,
				400
			);
		}

		return $result['result'];
	}
}

