<?php

namespace Limb_Chatbot\Includes\Integrations\Telegram\Utilities;

use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Users\Users_Endpoint;
use Limb_Chatbot\Includes\Integrations\Telegram\Services\Telegram_Agent_Service;
use Limb_Chatbot\Includes\Integrations\Telegram\Telegram;
use Limb_Chatbot\Includes\Integrations\Telegram\Utilities\Messages_Utility;

/**
 * Telegram Users Utility
 *
 * Utility for Telegram private chat user operations.
 * Wraps the Users_Endpoint with context-aware configuration.
 *
 * Private chats are identified by type="private" in Telegram API.
 * User data includes: id, first_name, last_name, username, language_code.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Utilities
 * @since 1.0.11
 */
class Users_Utility {

	/**
	 * API endpoint handler for user operations.
	 *
	 * @var Users_Endpoint
	 * @since 1.0.11
	 */
	public Users_Endpoint $endpoint;

	/**
	 * Telegram configuration object.
	 *
	 * @var Config|null
	 * @since 1.0.11
	 */
	public ?Config $config = null;

	/**
	 * HTTP request timeout in seconds.
	 *
	 * @var int
	 * @since 1.0.11
	 */
	public int $timeout = 30;

	/**
	 * Specific chat ID for single chat operations.
	 *
	 * @var string|int|null
	 * @since 1.0.11
	 */
	public $chat_id = null;

	/**
	 * Specific user ID for single user operations.
	 *
	 * @var int|null
	 * @since 1.0.11
	 */
	public ?int $user_id = null;

	/**
	 * Constructor.
	 *
	 * Initializes the utility with config and instantiates the related API endpoint.
	 *
	 * @param Config|null $config Configuration object.
	 *
	 * @since 1.0.11
	 */
	public function __construct( ?Config $config = null ) {
		if ( is_null( $config ) ) {
			$this->config = Config::where( [
				'default'    => true,
				'related_to' => Telegram::$id,
			] )->first();
		} else {
			$this->config = $config;
		}

		// Initialize endpoint
		$this->endpoint = new Users_Endpoint( $this );
	}

	/**
	 * List all private chat users.
	 *
	 * @return array Array of user objects.
	 * @since 1.0.11
	 */
	public function list(): array {
		return $this->endpoint->list();
	}

	/**
	 * Retrieve a single chat/user.
	 *
	 * @return array Chat object with user details.
	 * @since 1.0.11
	 */
	public function retrieve(): array {
		return $this->endpoint->retrieve();
	}

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

	/**
	 * Get timeout value.
	 *
	 * @return int
	 * @since 1.0.11
	 */
	public function get_timeout(): int {
		return $this->timeout;
	}

	/**
	 * Set chat ID for single chat operations.
	 *
	 * @param string|int $chat_id Chat ID.
	 *
	 * @return self
	 * @since 1.0.11
	 */
	public function set_chat_id( $chat_id ): self {
		$this->chat_id = $chat_id;

		return $this;
	}

	/**
	 * Set user ID for single user operations (e.g., fetching profile photos).
	 *
	 * @param int $user_id Telegram user ID.
	 *
	 * @return self
	 * @since 1.0.11
	 */
	public function set_user_id( int $user_id ): self {
		$this->user_id = $user_id;

		return $this;
	}

	/**
	 * List users with profile photos.
	 *
	 * Fetches users and enriches them with profile photo URLs.
	 *
	 * @return array Array of user objects with profile_photo_url field.
	 * @since 1.0.11
	 */
	public function list_with_profile_photos(): array {
		$users = $this->endpoint->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_Utility to fetch photos
		$messages_utility = new Messages_Utility( $this->config );

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

		return $users;
	}

	/**
	 * List users and create agents for them.
	 *
	 * Fetches users, enriches with profile photos, and creates WordPress/Chatbot users.
	 *
	 * @return array Array of results with user data and agent creation status.
	 * @since 1.0.11
	 */
	public function list_and_create_agents(): array {
		$users = $this->list_with_profile_photos();

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

	/**
	 * Create agents for users.
	 *
	 * @param array $users Array of user objects.
	 *
	 * @return array Results with agent creation status.
	 * @since 1.0.11
	 */
	private function create_agents_for_users( array $users ): array {
		if ( empty( $users ) ) {
			return [];
		}

		$agent_service = new Telegram_Agent_Service();
		$results       = [];

		foreach ( $users as $user ) {
			$result = [
				'user'          => $user,
				'agent'         => null,
				'agent_exists'  => false,
				'agent_created' => false,
			];

			try {
				$chatbot_user = $agent_service->get_or_create_agent_from_telegram_user( $user, $this->config );

				if ( $chatbot_user ) {
					$result['agent']        = $chatbot_user;
					$result['agent_exists'] = true;

					// Check if it was just created (simplified check)
					$telegram_id = $user['id'] ?? '';
					$existing    = $agent_service->get_chatbot_user_by_telegram_id( (string) $telegram_id, $this->config );
					$result['agent_created'] = $existing ? false : true;
				}
			} catch ( \Exception $e ) {
				$result['error'] = $e->getMessage();
			}

			$results[] = $result;
		}

		return $results;
	}
}
