<?php

	use Reflect\{Response, Path};
	use Reflect\Rules\{Ruleset, Rules, Type};

	use VLW\API\API;
	use VLW\Database\Models\Coffee\Coffee;
	use VLW\Database\Tables\Coffee\Coffee as CoffeeTable;

	require_once Path::root("src/API/API.php");
	require_once Path::root("src/Database/Models/Coffee/Coffee.php");
	require_once Path::root("src/Database/Tables/Coffee/Coffee.php");

	final class POST_Coffee extends API {
		public function __construct() {
			parent::__construct(new Ruleset(strict: true)->POST([
				new Rules(CoffeeTable::DATE_CREATED->value)
					->type(Type::STRING)
					->type(Type::NUMBER)
					->default(null)
			]));
		}

		public function main(): Response {
			$datetime = new DateTimeImmutable();

			// Parse DateTime from POST string
			if ($_POST[CoffeeTable::DATE_CREATED->value]) {
				try {
					// Create DateTimeImmutable from Unix timestamp or datetime string
					$datetime = gettype($_POST[CoffeeTable::DATE_CREATED->value]) === "integer"
						? DateTimeImmutable::createFromTimestamp($_POST[CoffeeTable::DATE_CREATED->value])
						: new DateTimeImmutable($_POST[CoffeeTable::DATE_CREATED->value]);
				} catch (DateMalformedStringException $error) {
					return new Response($error->getMessage(), 400);
				}
			}

			return new Response(Coffee::new($datetime));
		}
	}