<?php

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

use Limb_Chatbot\Includes\Integrations\Telegram\Handlers\Response_Handler;

/**
 * Users Response Handler
 *
 * Specialized response handler for Telegram user/private chat endpoints.
 * Handles response parsing and formatting for private chat user data.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Endpoints\Users
 * @since 1.0.11
 */
class Users_Response_Handler extends Response_Handler {

	/**
	 * Get formatted users from response.
	 *
	 * Parses updates to find unique users from private chats.
	 *
	 * @return array Array of formatted user objects.
	 * @since 1.0.11
	 */
	public function get_users(): array {
		$body   = $this->get_body();
		$updates = $body['result'] ?? [];

		if ( ! is_array( $updates ) ) {
			return [];
		}

		$users    = [];
		$seen_ids = [];

		foreach ( $updates as $update ) {
			$user = $this->extract_user_from_update( $update );

			if ( ! $user ) {
				continue;
			}

			if ( isset( $seen_ids[ $user['id'] ] ) ) {
				continue;
			}

			$seen_ids[ $user['id'] ] = true;
			$users[]                 = $user;
		}

		return $users;
	}

	/**
	 * Extract user data from a single update.
	 *
	 * Checks for private messages and my_chat_member updates.
	 *
	 * @param array $update Telegram update object.
	 * @return array|null User data or null if not applicable.
	 */
	private function extract_user_from_update( array $update ): ?array {
		$chat = null;
		$from = null;

		// Check my_chat_member events (user started/blocked bot)
		if ( isset( $update['my_chat_member'] ) ) {
			$chat_member = $update['my_chat_member'];
			$chat        = $chat_member['chat'] ?? null;
			$from        = $chat_member['from'] ?? null;
			$new_status  = $chat_member['new_chat_member']['status'] ?? 'member';

			// Skip if user blocked the bot
			if ( in_array( $new_status, [ 'left', 'kicked' ], true ) ) {
				return null;
			}
		}
		// Check message events from private chats
		elseif ( isset( $update['message'] ) ) {
			$chat = $update['message']['chat'] ?? null;
			$from = $update['message']['from'] ?? null;
		}

		// Skip if no chat or not a private chat
		if ( ! $chat || ( $chat['type'] ?? '' ) !== 'private' ) {
			return null;
		}

		// Skip bots
		if ( ! empty( $from['is_bot'] ) ) {
			return null;
		}

		$user_id = $from['id'] ?? $chat['id'] ?? null;

		if ( empty( $user_id ) ) {
			return null;
		}

		return [
			'id'            => $user_id,
			'chat_id'       => $chat['id'] ?? $user_id,
			'first_name'    => $from['first_name'] ?? $chat['first_name'] ?? '',
			'last_name'     => $from['last_name'] ?? $chat['last_name'] ?? '',
			'username'      => $from['username'] ?? $chat['username'] ?? '',
			'language_code' => $from['language_code'] ?? '',
			'type'          => 'private',
		];
	}
}

