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

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

// Built-in libraries
use exception;


/**
 * Model of category
 *
 * @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 category extends core implements document_interface, collection_interface
{
	use document_trait;

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

	/**
	 * Write the category
	 *
	 * @param int $identifier Identifier (unique)
	 * @param array $name Name [['en' => value], ['ru' => значение]]
	 * @param int|null $position Position for soring in the catalog (ASC)
	 * @param array &$errors Registry of errors
	 *
	 * @return string|null Identifier (_id) of the document in ArangoDB, if created
	 *
	 * @todo
	 * 1. Bind parameters
	 */
	public static function write(
		int $identifier,
		array $name = [['en' => 'ERROR']],
		?int $position = null,
		array &$errors = []
	): string|null {
		try {
			if (collection::initialize(static::COLLECTION, static::TYPE, errors: $errors)) {
				// Initialized the collection

				// Writing to ArangoDB and exit (success)
				return document::write(
					static::COLLECTION,
					[
						'identifier' => $identifier,
						'name' => $name,
						'position' => $position,
						'version' => ROBOT_VERSION
					],
					errors: $errors
				);
			} 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;
	}
}
