<?php

namespace Api\Users\Permissions;

use Exception;
use Khofmann\Api\Api;
use Khofmann\Input\Input;
use Khofmann\Models\User\User;
use Khofmann\Response\Response;
use Khofmann\ApiError\ApiError;
use Khofmann\Request\Request;

/**
 * User permissions route handlers
 */
class Permissions extends Api
{
  /**
   * Permissions PATCH handler
   *
   * Sets user admin or not.
   *
   * Returns updated user.
   *
   * @param mixed $id User ID
   *
   * @throws 404 User not found
   * @throws 500 Failed to update user permissions
   */
  public function patch($id): void
  {
    // Fetch all inputs.
    $isAdmin = Input::post("isAdmin");

    // Try and update user image.
    // Throw errors according to situation.
    try {
      Response::json(User::getByID($id)->updatePermissions($isAdmin));
    } catch (Exception $err) {
      switch ($err->getMessage()) {
        case "NotFound":
          throw ApiError::notFound("user");
        default:
          // Due to how the failed field is handled, it's ApiError is inside the models update
          throw $err;
      }
    }
  }
}
