<?php

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

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

/**
 * Slack Channels Endpoint
 *
 * Handles channel-related operations with the Slack API including:
 * - Listing channels (conversations.list)
 * - Retrieving single channel info (conversations.info)
 * - Handling pagination for large workspaces
 *
 * @package Limb_Chatbot\Includes\Integrations\Slack\Endpoints
 * @since 1.0.0
 */
class Channels_Endpoint extends Slack_Endpoint {

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

	/**
	 * List channels from Slack workspace.
	 *
	 * Fetches all channels based on utility configuration (types, archived status, etc.).
	 * Handles pagination automatically to retrieve all channels.
	 *
	 * @return array Array of channel objects.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function list() {
		$http_client  = $this->http_client_factory();
		$all_channels = [];
		$cursor       = null;

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

			$url      = self::API_BASE_URL . '/conversations.list';
			$response = $http_client->get(
				$url,
				[
					'headers' => $this->get_header(),
					'timeout' => $this->utility->get_timeout(),
				]
			);

			$handler  = new Channels_Response_Handler( $response, $http_client, $this );
			$result   = $handler->get_body();
			$channels = $result['channels'] ?? [];

			$all_channels = array_merge( $all_channels, $channels );
			$all_channels = array_filter( $all_channels, function ( $item ) {
				return ! empty( $item['is_member'] );
			} );
			$cursor       = $result['response_metadata']['next_cursor'] ?? null;
		} while ( ! empty( $cursor ) );

		return $all_channels;
	}

	/**
	 * Retrieve a single channel by ID.
	 *
	 * @return array Channel object with full details.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function retrieve() {
		$http_client = $this->http_client_factory();
		$url         = self::API_BASE_URL . '/conversations.info?' . http_build_query( [
				'channel' => $this->utility->channel_id,
			] );

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

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

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

