<?php

	namespace VLW\Database\Models\Work;

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

	use VLW\Helpers\UUID;
	use VLW\Database\Database;
	use VLW\Database\Models\Model;
	use VLW\Database\Models\Work\Work;
	use VLW\Database\Tables\Work\{Tags, TagsLabelEnum};

	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/Models/Work/Work.php");
	require_once VV::root("src/Database/Tables/Work/Tags.php");

	class Tag extends Model {
		final public static function new(Work $work, TagsLabelEnum $label): self {
			$id = UUID::v4();

			if (!parent::create(TimelineTable::TABLE, [
				TimelineTable::ID->value           => $id,
				TimelineTable::REF_WORK_ID->value  => $work->id,
				TimelineTable::LABEL->value        => $label->name
			])) { throw new Exception("Failed to create Work Tag entity"); }

			return new Tag($id);
		}

		final public static function from(Work $work): array {
			return array_map(fn(array $tag): Tag => new Tag($tag[Tags::ID->value]), new Database()
				->from(Tags::TABLE)
				->where([Tags::REF_WORK_ID->value => $work->id])
				->order([Tags::LABEL->value => Order::DESC])
				->select(Tags::ID->value)
				->fetch_all(MYSQLI_ASSOC)
			);
		}

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

		final public Work $work {
			get              => new Work($this->get(Tags::REF_WORK_ID->value));
			set (Work $work) => $this->set(Tags::REF_WORK_ID->value, $work);
		}

		final public TagsLabelEnum $label {
			get                           => TagsLabelEnum::fromName($this->get(Tags::LABEL->value));
			set (TagsLabelEnum $pathname) => $this->set(Tags::LABEL->value, $pathname->name);
		}
	}