<?php

namespace SHServ\Models;

use \SHServ\Entities\Meta;

class MetaManager extends \SHServ\Middleware\Model {
	public function get_all_by_entity(String $assignment, int $ent_id): Array {
		$result = $this -> thin_builder() -> select(
			Meta::$table_name,
			Meta::get_fields(),
			[
				[ "assignment", "=", $assignment ],
				"AND",
				[ "ent_id", "=", $ent_id ]
			]
		);

		if(!$result) {
			return [];
		}

		return array_map(function ($item) {
			return new Meta($item["id"], $item);
		}, $result);
	}

	public function get_one_by_name(String $name, String $assignment, int $ent_id): Meta | null {
		$result = $this -> thin_builder() -> select(
			Meta::$table_name,
			Meta::get_fields(),
			[
				[ "assignment", "=", $assignment ],
				"AND",
				[ "ent_id", "=", $ent_id ],
				"AND",
				[ "name", "=", $name ]
			]
		);

		if(!$result) {
			return null;
		}

		return new Meta($result[0]["id"], $result[0]);
	}

	public function remove_all_by_entity(String $assignment, int $ent_id): bool {
		$this -> thin_builder() -> delete(
			Meta::$table_name,
			[
				[ "assignment", "=", $assignment ],
				"AND",
				[ "ent_id", "=", $ent_id ]
			]
		);
		return true;
	}

	public function create(String $name, String $value, String $assignment, int $ent_id): int {
		$result = $this -> thin_builder() -> insert(
			Meta::$table_name,
			[
				"name" => $name,
				"value" => $value,
				"assignment" => $assignment,
				"ent_id" => $ent_id,
				"create_at" => date("Y-m-d H:i:s")
			]
		);

		return $result ? $result : 0;
	}

	public function create_or_update(String $name, String $value, String $assignment, int $ent_id): bool {
		$tb = $this -> thin_builder();
		$tb -> beginTransaction();
		try {
			$entry = $this -> get_one_by_name($name, $assignment, $ent_id);

			if($entry) {
				$entry -> value = $value;
				$result = $entry -> update();
			} else {
				$result = $this -> create($name, $value, $assignment, $ent_id);
			}

			$tb -> commit();
			return $result ? true : false;
		} catch (\Throwable $e) {
			if($tb -> inTransaction()) {
				$tb -> rollBack();
			}
			throw $e;
		}
	}
}