<?php

declare(strict_types=1);

namespace mirzaev\huesos\models;

// Files of the project
use mirzaev\huesos\models\core,
	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;

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

// Built-in libraries
use exception;

/**
 * Model of settings
 *
 * @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 settings extends core implements document_interface, collection_interface
{
	use 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
						if (isset($result->language)) $result->language = language::{$result->language};
						if (isset($result->currency)) $result->currency = currency::{$result->currency};

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

						// Exit (success)
						return $settings;
					} else throw new exception('Class ' . static::class . ' does not implement a document from ArangoDB');
				} 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;
	}
}
