<?php

declare(strict_types=1);

namespace mirzaev\arming_bot\models;

// Files of the project
use mirzaev\arming_bot\models\core,
	mirzaev\arming_bot\models\traits\status,
	mirzaev\arming_bot\models\traits\document as arangodb_document_trait,
	mirzaev\arming_bot\models\interfaces\document as arangodb_document_interface,
	mirzaev\arming_bot\models\enumerations\language;

// Framework for ArangoDB
use mirzaev\arangodb\collection,
	mirzaev\arangodb\document;

// Framework for Telegram
use Zanzara\Telegram\Type\User as telegram;

// Library for ArangoDB
use ArangoDBClient\Document as _document;

// Built-in libraries
use exception;

/**
 * Model of account
 *
 * @package mirzaev\arming_bot\models
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class account extends core implements arangodb_document_interface
{
	use status, arangodb_document_trait;

	/**
	 * Name of the collection in ArangoDB
	 */
	final public const string COLLECTION = 'account';

	/**
	 * Initialize
	 *
	 * @param int $identifier Identifier of the account
	 * @param telegram|array|null $registration Данные для регистрация, если аккаунт не найден
	 * @param array &$errors Registry of errors
	 *
	 * @return static|null Объект аккаунта, если найден
	 */
	public static function initialize(int $identifier, telegram|array|null $registration = null, array &$errors = []): static|null
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Initialized the collection

				// Initializing the account
				$result = collection::execute(
					<<<'AQL'
						FOR d IN @@collection 
							FILTER d.identifier == @identifier 
							RETURN d
						AQL,
					[
						'@collection' => static::COLLECTION,
						'identifier' => $identifier
					],
					errors: $errors
				);

				if ($result instanceof _document) {
					// Initialized the account

					// Initializing the object
					$account = new account;

					if (method_exists($account, '__document')) {
						// Object can implement a document from ArangoDB

						// Abstractioning of parameters
						$result->language = language::{$result->language} ?? 'en';

						// Writing the instance of account document from ArangoDB to the implement object
						$account->__document($result);

						// Exit (success)
						return $account;
					}
				} else if ($registration) {
					// Not found the account and registration is requested

					// Creating account
					$_id = document::write(
						static::COLLECTION,
						(is_array($registration)
							? $registration :
							[
								'identifier' => $registration->getId(),
								'name' => [
									'first' => $registration->getFirstName(),
									'last' => $registration->getLastName()
								],
								'domain' => $registration->getUsername(),
								'robot' => $registration->isBot(),
								'menus' => [
									'attachments' => $registration->getAddedToAttachmentMenu()
								],
								'messages' => true,
								'groups' => [
									'join' => $registration->getCanJoinGroups(),
									'messages' => $registration->getCanReadAllGroupMessages()
								],
								'premium' => $registration->isPremium(),
								'language' => language::{$registration->getLanguageCode()}->name ?? 'en',
								'queries' => [
									'inline' => $registration->getSupportsInlineQueries()
								]
							]) + [
							'banned' => false,
							'tester' => false,
							'developer' => false,
							'access' => [
								'settings' => false
							],
							'version' => ROBOT_VERSION,
							'active' => true
						],
						errors: $errors
					);

					if ($_id) {
						// Created account

						// Initializing of the account (without registration request)
						return static::initialize($identifier, errors: $errors);
					} else throw new exception('Failed to register account');
				} else throw new exception('Failed to find account');
			} else throw new exception('Failed to initialize ' . static::TYPE . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}
}
