<?php

declare(strict_types=1);

final class UserPostController extends AbstractController
{
	protected string $route = '/api/v1/user';
	protected array $mandatoryAttributes = [
		'username',
		'password',
		'email',
		'jabberAddress',
	];

	public function handle(): void
	{
		if (!$this->isUserLoggedIn()) {
			return;
		}

		if (!$this->session->isAdmin()) {
			$this->response = new ApiJsonResponse(ServerStatus::UNAUTHORIZED);
			$this->response->setSuccess(false);
			$this->response->setMessage('You have no permission!');
		}

		parent::handle();

		if ($this->response->getStatus() !== ServerStatus::OK) {
			return;
		}

		try {
			$user = new User();

			$user->setUsername($this->jsonBody->username);
			$user->setPassword(Password::GetHash($this->jsonBody->password));
			$user->setEmail($this->jsonBody->email);
			$user->setJabberAddress($this->jsonBody->jabberAddress);
			$user->Save();

			$this->response = new ApiJsonResponse();
			$this->response->setParameter('userId', $user->getUserId());
		} catch (DatabaseException $e) {
			$this->response = new ApiJsonResponse(ServerStatus::INTERNAL_ERROR);
			$this->response->setParameter('success', false);
			$this->response->setMessage($e->getMessage());
		} catch (Throwable $e) {
			$this->response = new ApiJsonResponse(ServerStatus::BAD_REQUEST);
			$this->response->setParameter('success', false);
			$this->response->setMessage($e->getMessage());
		}
	}
}