<?php

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

use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Integrations\Slack\Endpoints\Slack_Endpoint;
use Limb_Chatbot\Includes\Integrations\Slack\Utilities\Users_Utility;

/**
 * Slack Users Endpoint
 *
 * Handles user-related operations with the Slack API including:
 * - Listing users (users.list)
 * - Handling pagination for large workspaces
 *
 * @package Limb_Chatbot\Includes\Integrations\Slack\Endpoints
 * @since 1.0.0
 */
class Users_Endpoint extends Slack_Endpoint {

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

	/**
	 * List users from Slack workspace.
	 *
	 * Fetches all users from the Slack workspace.
	 * Handles pagination automatically to retrieve all users.
	 * Filters out bots and deleted users by default.
	 *
	 * @return array Array of user objects.
	 * @since 1.0.0
	 */
	public function list() {
		$http_client = $this->http_client_factory();
		$all_users   = [];
		$cursor      = null;

		do {
			$params = [];
			if ( $cursor ) {
				$params['cursor'] = $cursor;
			}

			$url      = self::API_BASE_URL . '/users.list';
			if ( ! empty( $params ) ) {
				$url .= '?' . http_build_query( $params );
			}

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

			$handler = new Users_Response_Handler( $response, $http_client, $this );
			$result  = $handler->get_body();
			$users   = $result['members'] ?? [];

			// Filter out bots and deleted users
			$users = array_filter( $users, function ( $user ) {
				return ! ( $user['is_bot'] ?? false ) && ! ( $user['deleted'] ?? false );
			} );

			$all_users = array_merge( $all_users, $users );
			$cursor    = $result['response_metadata']['next_cursor'] ?? null;
		} while ( ! empty( $cursor ) );

		return $all_users;
	}

	/**
	 * Retrieve a single user by ID.
	 *
	 * @param string $user_id Slack user ID.
	 *
	 * @return array User object with full details.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function retrieve( string $user_id ) {
		$http_client = $this->http_client_factory();
		$url         = self::API_BASE_URL . '/users.info?' . http_build_query( [
				'user' => $user_id,
			] );

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

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

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

	/**
	 * Retrieve multiple users by their IDs.
	 *
	 * @param array $user_ids Array of Slack user IDs.
	 *
	 * @return array Array of user objects.
	 * @since 1.0.0
	 */
	public function retrieve_multiple( array $user_ids ) {
		$users = [];

		foreach ( $user_ids as $user_id ) {
			try {
				$user = $this->retrieve( $user_id );
				if ( ! empty( $user ) ) {
					// Filter out bots and deleted users
					if ( empty( $user['is_bot'] ) && empty( $user['deleted'] ) ) {
						$users[] = $user;
					}
				}
			} catch ( \Exception $e ) {
				// Continue on error, log if needed
				continue;
			}
		}

		return $users;
	}
}

