<?php

declare(strict_types=1);

final class UserAdminDeleteController extends AbstractController
{
	protected string $route = '/api/v1/user/{userId}/admin';

	private int $userId;

	public function __construct(string $url)
	{
		parent::__construct($url);
		$this->userId = (int)$this->getUrlParamInt('userId');
	}

	public function handle(): void
	{
		$this->response = new ApiJsonResponse();

		if (!$this->isUserLoggedIn()) {
			return;
		}

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

			return;
		}

		try {
			$user = new User($this->userId);
			$user->setAdmin(false);
			$user->Save();
		} catch (Throwable $e) {
			$this->response->setSuccess(false);
			$this->response->setStatus($e->getCode() !== 0 ? $e->getCode() : ServerStatus::BAD_REQUEST);
			$this->response->setMessage($e->getMessage());
		}
	}
}