<?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\Actions;

	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/Actions.php");

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

			if (!parent::create(Actions::TABLE, [
				Actions::ID->value           => $id,
				Actions::REF_WORK_ID->value  => $work->id,
				Actions::HREF->value         => null,
				Actions::CLASSLIST->value    => null,
				Actions::ICON_PREPEND->value => null,
				Actions::ICON_APPEND->value  => null
			])) { throw new Exception("Failed to create Work Action entity"); }

			return new Action($id);
		}

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

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

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

		final public int $order_idx {
			get                  => $this->get(TimelineTable::ORDER_IDX->value);
			set (int $order_idx) => $this->set(TimelineTable::ORDER_IDX->value, $order_idx);
		}

		final public ?string $href {
			get                 => $this->get(Actions::HREF->value);
			set (?string $href) => $this->set(Actions::HREF->value, $href);
		}

		final public string $text {
			get                => $this->get(Actions::TEXT->value);
			set (string $text) => $this->set(Actions::TEXT->value, $text);
		}

		final public ?string $classlist {
			get                      => $this->get(Actions::CLASSLIST->value);
			set (?string $classlist) => $this->set(Actions::CLASSLIST->value, $classlist);
		}

		final public ?string $icon_prepend {
			get                         => $this->get(Actions::ICON_PREPEND->value);
			set (?string $icon_prepend) => $this->set(Actions::ICON_PREPEND->value, $icon_prepend);
		}

		final public ?string $icon_append {
			get                        => $this->get(Actions::ICON_APPEND->value);
			set (?string $icon_append) => $this->set(Actions::ICON_APPEND->value, $icon_append);
		}
	}