<?php

	use Reflect\{Response, Path};
	use Reflect\Rules\{Ruleset, Rules, Type};

	use VLW\Database\Database;
	use VLW\Database\Tables\Messages\MessagesTable;

	require_once Path::root("src/Database/Database.php");
	require_once Path::root("src/Database/Tables/Messages/Messages.php");

	class POST_Messages extends Database {
		protected Ruleset $ruleset;

		public function __construct() {
			$this->ruleset = new Ruleset(strict: true);

			$this->ruleset->POST([
				(new Rules(MessagesTable::EMAIL->value))
					->type(Type::STRING)
					->max(255)
					->default(null),

				(new Rules(MessagesTable::MESSAGE->value))
					->required()
					->type(Type::STRING)
					->min(1)
					->max(parent::SIZE_TEXT)
			]);

			$this->ruleset->validate_or_exit();

			parent::__construct();
		}

		public function main(): Response {
			$_POST[MessagesTable::TIMESTAMP_CREATED->value] = time();

			return $this->db->for(MessagesTable::NAME)->insert($_POST) === true
				? new Response(null, 201)
				: new Response("Failed to send message", 500);
		}
	}