<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models;

// Files of the project
use kodorvan\neurobot\models\core;

// Svoboda time
use svoboda\time\statement as svoboda;

// Baza database
use mirzaev\baza\database,
	mirzaev\baza\column,
	mirzaev\baza\record,
	mirzaev\baza\enumerations\encoding,
	mirzaev\baza\enumerations\type;

// Active Record pattern
use mirzaev\record\interfaces\record as record_interface,
	mirzaev\record\traits\record as record_trait;

// Built-in libraries
use Exception as exception,
	RuntimeException as exception_runtime;

/**
 * Code
 *
 * @package kodorvan\neurobot\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 code extends core implements record_interface
{
	use record_trait;

	/**
	 * File
	 *
	 * @var string $database Path to the database file
	 */
	protected string $file = DATABASES . DIRECTORY_SEPARATOR . 'codes.baza';

	/**
	 * Database
	 *
	 * @var database $database The database
	 */
	public protected(set) database $database;

	/**
	 * Constructor
	 *
	 * @method record|null $record The record
	 *
	 * @return void
	 */
	public function __construct(?record $record = null)
	{
		// Initializing the database
		$this->database = new database()
			->encoding(encoding::utf8)
			->columns(
				new column('identifier', type::long_long_unsigned),
				new column('account', type::long_long_unsigned),
				new column('value', type::string, ['length' => 32]),
				new column('tariff', type::long_long_unsigned),
				new column('bundle',  type::long_long_unsigned),
				new column('activated', type::char),
				new column('updated', type::integer_unsigned),
				new column('created', type::integer_unsigned)
			)
			->connect($this->file);

		// Initializing the record
		$record instanceof record and $this->record = $record;
	}

	/**
	 * Write
	 *
	 * @param string|null $code The 32 symbols code (null for automatic cryptographic generation)
	 * @param int $tariff The tariff identifier (0 - empty)
	 * @param int $bundle The bundle identifier (0 - empty)
	 *
	 * @return int|false The record identifier, if created
	 */
	public function write(?string $code = null, int $tariff = 0, int $bundle = 0): int|false
	{
		$record = $this->database->record(
			$this->database->count() + 1,
			0,
			is_string($code) ? $code : bin2hex(random_bytes(16)),
			$tariff,
			$bundle,
			0,
			svoboda::timestamp(),
			svoboda::timestamp()
		);

		// Writing the record into the database
		$created = $this->database->write($record);

		// Exit (success)
		return $created ? $record->identifier : false;
	}
}
