<?php

	namespace VLW\Database\Models;

	use \VV;

	use VLW\API\{Client, Endpoints};

	require_once VV::root("src/API/API.php");
	require_once VV::root("src/API/Endpoints.php");

	abstract class Model {
		abstract public static function all(array $params = []): array;
		
		private array $row;

		public function __construct(
			public readonly ?Endpoints $endpoint = null,
			private readonly array $params = []
		) {
			if ($this->endpoint) {
				$this->assign(self::first(self::list($endpoint, $params)));
			}
		}

		public static function first(array $array): array {
			return $array && is_array(array_values($array)[0]) ? $array[0] : $array;
		}

		public static function list(Endpoints $endpoint, array $params = []): array {
			$resp = (new Client())->call($endpoint->value)->params($params)->get();
			return $resp->ok ? $resp->json() : [];
		}

		public function assign(array $row): self {
			$this->row = $row;
			return $this;
		}

		public function get(string $key): mixed {
			return $this->row[$key] ?? null;
		}
	}