<?php

namespace Api\Refresh;

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

class Refresh extends Api
{
  public function post(): void
  {
    // Fetch all required inputs.
    // Throw 400 error if a required one is missing.
    $token = Request::token();
    $refreshToken = Input::post("refreshToken");
    if (empty($refreshToken)) throw ApiError::missingField(["refreshToken"]);

    // Try and log in user.
    // Throw errors according to situation.
    try {
      Response::json(User::refresh($token, $refreshToken));
    } catch (Exception $err) {
      switch ($err->getMessage()) {
        case "Failed":
          throw ApiError::failed("Refresh failed");
        case "NotFound":
          throw ApiError::unauthorized("Not authorized");
        default:
          throw $err;
      }
    }
  }
}
