<?php

	namespace VLW\Database;

	use Reflect\Response;

	use vlw\MySQL\MySQL;

	class Database {
		public const SIZE_UUID    = 36;
		public const SIZE_TEXT    = 65535;
		public const SIZE_UINT8   = 2 ** 8 -1;
		public const SIZE_UINT16  = 2 ** 16 -1;
		public const SIZE_UINT32  = 2 ** 32 -1;
		public const SIZE_UINT64  = 2 ** 64 -1;
		public const SIZE_VARCHAR = 255;

		protected readonly MySQL $db;

		public function __construct() {
			// Create new MariaDB connection
			$this->db = new MySQL(
				$_ENV["server_database"]["host"],
				$_ENV["server_database"]["user"],
				$_ENV["server_database"]["pass"],
				$_ENV["server_database"]["db"],
			);
		}

		// Return all rows from a table using $_GET paramters as the WHERE clause as a Reflect\Response
		public function list(string $table, array $columns, array $order = null): Response {
			$resp = $this->db->for($table)->where(array_intersect_key($_GET, array_flip($columns)));

			// Optionally order rows by columns
			if ($order) {
				$resp = $resp->order($order);
			}

			// Return all matched rows or a 404 with an empty array if there were not results
			$resp = $resp->select($columns);
			return $resp && $resp->num_rows > 0
				? new Response($resp->fetch_all(MYSQLI_ASSOC))
				: new Response([], 404);
		}
	}