<?php

	use vlw\MySQL\Operators;
	use Reflect\{Response, Path, Call};
	use Reflect\Rules\{Ruleset, Rules, Type};

	use VLW\API\Endpoints;
	use VLW\Database\Database;
	use VLW\Database\Tables\Search\{SearchTable, SearchCategoryEnum};

	require_once Path::root("src/API/Endpoints.php");
	require_once Path::root("src/Database/Database.php");
	require_once Path::root("src/Database/Tables/Search/Search.php");

	class GET_Search extends Database {
		protected Ruleset $ruleset;

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

			$this->ruleset->GET([
				(new Rules(SearchTable::QUERY->value))
					->type(Type::STRING)
					->min(2)
					->max(parent::SIZE_VARCHAR)
					->default(null),

				(new Rules(SearchTable::ID->value))
					->type(Type::STRING)
					->min(1)
					->max(10)
					->default(null),

				(new Rules(SearchTable::CATEGORY->value))
					->type(Type::ENUM, SearchCategoryEnum::names())
					->default(null)
			]);

			$this->ruleset->validate_or_exit();

			parent::__construct();
		}

		private static function get_query(): string {
			preg_match_all("/[a-zA-Z0-9]+/", $_GET[SearchTable::QUERY->value], $matches);
			
			return strtolower(implode("", $matches[0]));
		}

		public function main(): Response {
			$result = $this->db->for(SearchTable::NAME);

			if ($_GET[SearchTable::ID->value]) {
				$result = $result->where([SearchTable::ID->value => $_GET[SearchTable::ID->value]]);
			} else if ($_GET[SearchTable::QUERY->value]) {
				$query = self::get_query();

				$filter = [
					SearchTable::QUERY->value => [
						Operators::LIKE->value => "%{$query}%"
					]
				];

				if ($_GET[SearchTable::CATEGORY->value]) {
					$filter[SearchTable::CATEGORY->value] = $_GET[SearchTable::CATEGORY->value];
				}

				$result = $result->where($filter);
			} else {
				new Response([], 400);
			}

			$result = $result->select([
				SearchTable::ID->value,
				SearchTable::TITLE->value,
				SearchTable::SUMMARY->value,
				SearchTable::CATEGORY->value,
				SearchTable::HREF->value
			]);
			
			return $result->num_rows > 0
				? new Response($result->fetch_all(MYSQLI_ASSOC))
				: new Response([], 404);
		}
	}