<?php

	namespace VLW\Helpers;

	use \VV;

	use VLW\Database\Database;
	use VLW\Database\Models\Work\Work;
	use VLW\Database\Models\Search\Search;
	use VLW\Database\Tables\Search\{Search as SearchTable, SearchTypeEnum};

	require_once VV::root("src/Database/Database.php");
	require_once VV::root("src/Database/Models/Work/Work.php");
	require_once VV::root("src/Database/Models/Search/Search.php");
	require_once VV::root("src/Database/Tables/Search/Search.php");

	class GenerateSearch {
		private readonly Database $db;

		public function __construct() {
			$this->db = new Database();
		}

		public function generate(): bool {
			$this->truncate();

			return $this->index_work();
		}

		private function truncate(): bool {
			return $this->db->from(SearchTable::TABLE)->delete();
		}

		private function index_work(): bool {
			foreach (Work::all() as $work) {
				// Construct a space separated fulltext query string from work entity data
				$query = strtolower(implode(" ", [
					$work->title,
					$work->summary ?? "",
					$work->date_created->format("Y"),
					$work->date_created->format("n"),
					$work->date_created->format("j"),
					SearchTypeEnum::WORK->name
				]));

				$search = Search::new($query, SearchTypeEnum::WORK, $work->title);
				if (!$search) { return false; }

				$search->text = $work->summary;
				// Use href from first Work Action if set or default to "about" page from namespace
				$search->href = $work->actions() ? $work->actions()[0]->href : "/work/{$work->namespace}";
			}

			return true;
		}
	}