<?php

	namespace VLW\Database\Models\Messages;

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

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

	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/Messages/Messages.php");

	class Message extends Model {
		final public static function new(string $message, ?string $email = null): self {
			$id = UUID::v4();

			if (!parent::create(Messages::TABLE, [
				Messages::ID->value           => $id,
				Messages::EMAIL->value        => $email,
				Messages::MESSAGE->value      => $message,
				Messages::DATE_CREATED->value => date(parent::DATE_FORMAT)
			])) { throw new Exception("Failed to create Message entity"); }

			return new Message($id);
		}

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

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

		final public ?string $email {
			get                  => $this->get(Messages::EMAIL->value);
			set (?string $email) => $this->set(Messages::EMAIL->value, $email);
		}

		final public string $message {
			get                   => $this->get(Messages::MESSAGE->value);
			set (string $message) => $this->set(Messages::MESSAGE->value, $message);
		}

		final public DateTimeImmutable $date_created {
			get                                   => new DateTimeImmutable($this->get(Messages::DATE_CREATED->value));
			set (DateTimeImmutable $date_created) => $this->set(Messages::DATE_CREATED->value, $date_created->format(parent::DATE_FORMAT));
		}
	}