<?php
/**
 * Browser chat session identity and history.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Browser_Session {
	private $telegram;
	private $conversation_store;
	private $callbacks;

	public function __construct( $telegram = null, $conversation_store = null, $callbacks = array() ) {
		$this->telegram           = $telegram;
		$this->conversation_store = $conversation_store;
		$this->callbacks          = is_array( $callbacks ) ? $callbacks : array();
	}

	public function get_session_id( $user_id = 0 ) {
		$shared_session_id = $this->get_shared_founder_session_id();
		if ( '' !== $shared_session_id ) {
			return $shared_session_id;
		}

		$user_id = max( 0, intval( $user_id ) );
		if ( $user_id < 1 && function_exists( 'get_current_user_id' ) ) {
			$user_id = intval( get_current_user_id() );
		}
		if ( $user_id < 1 ) {
			$user_id = 1;
		}

		return 'admin-ui-' . $user_id;
	}

	public function get_shared_founder_chat_id() {
		if ( ! $this->telegram || ! method_exists( $this->telegram, 'get_settings' ) ) {
			return '';
		}

		$settings = (array) $this->telegram->get_settings();
		$chat_id  = isset( $settings['owner_chat_id'] ) ? preg_replace( '/[^0-9\\-]/', '', (string) $settings['owner_chat_id'] ) : '';

		return is_string( $chat_id ) ? $chat_id : '';
	}

	public function get_shared_founder_session_id() {
		$chat_id = $this->get_shared_founder_chat_id();
		if ( '' === $chat_id ) {
			return '';
		}

		return (string) $this->call( 'get_founder_session_id', array( $chat_id ), '' );
	}

	public function get_history( $user_id = 0 ) {
		$session_id = $this->get_session_id( $user_id );
		if ( ! $this->conversation_store || '' === $session_id ) {
			return array();
		}

		return (array) $this->conversation_store->get( $session_id );
	}

	public function get_display_history( $user_id = 0, $filters = array() ) {
		$session_id = $this->get_session_id( $user_id );
		if ( '' === $session_id ) {
			return array();
		}

		$filters = is_array( $filters ) ? $filters : array();
		if ( $this->conversation_store && method_exists( $this->conversation_store, 'get_display_history' ) ) {
			$filters['channel'] = 'admin_ui';

			return (array) $this->conversation_store->get_display_history( $session_id, $filters );
		}

		return $this->get_history( $user_id );
	}

	private function call( $name, $args = array(), $default = null ) {
		return Niwa_AI_Admin_Autonomy_Callbacks::call( $this->callbacks, $name, $args, $default );
	}
}
