<?php

	namespace VLW\Database\Models\Coffee;

	use \VV;
	use \Exception;
	use \vlw\MySQL\Order;
	use \DateTimeImmutable;

	use VLW\Helpers\UUID;
	use VLW\Database\Database;
	use VLW\Database\Models\Model;
	use VLW\Database\Tables\Coffee\{Stats, Coffee as CoffeeTable};

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

	class Coffee extends Model {
		final public static function new(?DateTimeImmutable $datetime = null): self {
			$id = UUID::v4();

			if (!parent::create(CoffeeTable::TABLE, [
				CoffeeTable::ID->value           => $id,
				CoffeeTable::DATE_CREATED->value => $datetime ? $datetime->format(parent::DATE_FORMAT) : date(parent::DATE_FORMAT)
			])) { throw new Exception("Failed to create Work entity"); }

			return new Coffee($id);
		}

		final public static function all(): array {
			return array_map(fn(array $work): Coffee => new Coffee($work[CoffeeTable::ID->value]), new Database()
				->from(CoffeeTable::TABLE)
				->order([CoffeeTable::DATE_CREATED->value => Order::DESC])
				->select(CoffeeTable::ID->value)
				->fetch_all(MYSQLI_ASSOC)
			);
		}

		final public static function count_week(): int {
			return new Database()
				->from(Stats::TABLE)
				->limit(1)
				->select(Stats::COUNT_WEEK->value)
				->fetch_assoc()[Stats::COUNT_WEEK->value] ?? 0;
		}

		final public static function count_week_average(): int {
			return new Database()
				->from(Stats::TABLE)
				->limit(1)
				->select(Stats::COUNT_WEEK_AVERAGE->value)
				->fetch_assoc()[Stats::COUNT_WEEK_AVERAGE->value] ?? 0;
		}

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

		public function delete(): bool {
			try {
				return $this->db->from(CoffeeTable::TABLE)->delete([CoffeeTable::ID->value => $this->id]);
			} catch (Exception $error) {
				return false;
			}
		}

		final public DateTimeImmutable $date_created {
			get                                   => new DateTimeImmutable($this->get(CoffeeTable::DATE_CREATED->value));
			set (DateTimeImmutable $date_created) => $this->set(CoffeeTable::DATE_CREATED->value, $date_created->format(parent::DATE_FORMAT));
		}
	}