<?php

namespace Limb_Chatbot\Includes\Integrations\Slack\Utilities;

use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\Integrations\Slack\Endpoints\Users\Users_Endpoint;
use Limb_Chatbot\Includes\Integrations\Slack\Slack;
use Limb_Chatbot\Includes\Utilities\Slack_Users_Utility as Global_Utility;

/**
 * Slack Users Utility
 *
 * Provider-specific utility for Slack user operations.
 * Wraps the Users_Endpoint with context-aware configuration.
 *
 * @package Limb_Chatbot\Includes\Integrations\Slack\Utilities
 * @since 1.0.0
 */
class Users_Utility {

	/**
	 * Global utility instance holding context.
	 *
	 * @var Global_Utility
	 * @since 1.0.0
	 */
	public Global_Utility $global_utility;

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

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

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

	/**
	 * Constructor.
	 *
	 * Initializes the utility with global context, loads the config if not set,
	 * and instantiates the related API endpoint.
	 *
	 * @param Global_Utility $global_utility Global utility object containing config.
	 *
	 * @since 1.0.0
	 */
	public function __construct( Global_Utility $global_utility ) {
		$this->global_utility = $global_utility;
		// Load default config if not set
		if ( is_null( $this->global_utility->config ) ) {
			$this->config = Config::where( [
				'default'    => true,
				'related_to' => Slack::class,
			] )->first();
		} else {
			$this->config = $this->global_utility->config;
		}

		// Copy properties from global utility
		$this->timeout = $this->global_utility->get_timeout();

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

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

	/**
	 * Retrieve a single user by ID.
	 *
	 * @param string $user_id Slack user ID.
	 *
	 * @return array User object.
	 * @since 1.0.0
	 */
	public function retrieve( string $user_id ) {
		return $this->endpoint->retrieve( $user_id );
	}

	/**
	 * 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 ) {
		return $this->endpoint->retrieve_multiple( $user_ids );
	}

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

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

