<?php

declare(strict_types=1);

namespace mirzaev\huesos\models;

// Files of the project
use mirzaev\huesos\models\core,
	mirzaev\huesos\models\traits\status,
	mirzaev\huesos\models\traits\buffer,
	mirzaev\huesos\models\traits\cart,
	mirzaev\huesos\models\traits\document as document_trait,
	mirzaev\huesos\models\interfaces\document as document_interface,
	mirzaev\huesos\models\interfaces\collection as collection_interface,
	mirzaev\huesos\models\enumerations\language,
	mirzaev\huesos\models\enumerations\currency;

// 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\huesos\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 document_interface, collection_interface
{
	use status, document_trait, buffer, cart {
		buffer::write as write;
		cart::initialize as cart;
	}

	/**
	 * 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 static;

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

						// Abstractioning of parameters
						if (isset($result->language)) $result->language = language::{$result->language};
						if (isset($result->currency)) $result->currency = currency::{$result->currency};

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

						// Exit (success)
						return $account;
					} else throw new exception('Class ' . static::class . ' does not implement a document from ArangoDB');
				} 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->name . ' collection: ' . static::COLLECTION);
		} catch (exception $e) {
var_dump($errors);
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return null;
	}
}
