<?php

	namespace VLW\Database\Models\Languages;

	use \VV;
	use \vlw\MySQL\Order;

	use VLW\Helpers\UUID;
	use VLW\Database\Database;
	use VLW\Database\Models\Model;
	use VLW\Database\Tables\Languages\Languages;

	require_once VV::root("src/Helpers/UUID.php");
	require_once VV::root("src/Database/Database.php");
	require_once VV::root("src/Database/Models/Model.php");
	require_once VV::root("src/Database/Tables/Languages/Languages.php");

	class Language extends Model {
		final public static function new(string $name, ?int $bytes = 0): self {
			$id = UUID::v4();

			if (!parent::create(Languages::TABLE, [
				Languages::ID->value    => $id,
				Languages::NAME->value  => $name,
				Languages::BYTES->value => $bytes
			])) { throw new Exception("Failed to create Language entity"); }

			return new Language($id);
		}

		final public static function all(): array {
			return array_map(fn(array $language): Language => new Language($language[Languages::ID->value]), new Database()
				->from(Languages::TABLE)
				->order([Languages::BYTES->value => Order::DESC])
				->select(Languages::ID->value)
				->fetch_all(MYSQLI_ASSOC)
			);
		}

		final public static function from(string $name): ?self {
			return array_map(fn(array $language): Language => new Language($language[Languages::ID->value]), new Database()
				->from(Languages::TABLE)
				->where([Languages::NAME->value => $name])
				->limit(1)
				->select(Languages::ID->value)
				->fetch_all(MYSQLI_ASSOC)
			);
		}

		public function __construct(public readonly string $id) {
			parent::__construct(Languages::TABLE, Languages::values(), [
				Languages::ID->value => $this->id
			]);
		}

		final public string $name {
			get                => $this->get(Languages::NAME->value);
			set (string $name) => $this->set(Languages::NAME->value, $name);
		}

		final public int $bytes {
			get              => $this->get(Languages::BYTES->value);
			set (int $bytes) => $this->set(Languages::BYTES->value, $bytes);
		}
	}