<?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\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;

// Library для ArangoDB
use ArangoDBClient\Document as _document;

// Built-in libraries
use exception;

/**
 * Model of settings
 *
 * @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 settings extends core implements arangodb_document_interface
{
	use arangodb_document_trait;

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

	/**
	 * Search for active settings
	 *
	 * @param array|null $create Данные для создания, если настройки не найдены
	 * @param array &$errors Registry of errors
	 *
	 * @return static|null Object implements the instance of settngs document from ArangoDB
	 */
	public static function active(array|null $create = null, array &$errors = []): static|null
	{
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Initialized the collection

				// Search for active settings
				$result = collection::execute(
					<<<'AQL'
					FOR d IN @@collection 
						FILTER d.status == 'active' 
						SORT d.updated DESC 
						LIMIT 1 
						RETURN d
					AQL,
					[
						'@collection' => static::COLLECTION
					],
					errors: $errors
				);

				if ($result instanceof _document) {
					// Found active settings

					// Initializing the object
					$settings = new static;

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

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

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

						// Exit (success)
						return $settings;
					}
				} else if ($create) {
					// Not found active settings and requested their creating

					// Creating a settings
					document::write(static::COLLECTION, ['status' => 'active'] + $create, errors: $errors);

					// Re-search (without creating) and exit (success || fail)
					return static::active(errors: $errors);
				} else throw new exception('Active settings not found');
			} 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;
	}
}
