<?php

namespace Api\Users\Posts;

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

/**
 * User posts route handlers
 */
class Posts extends Api
{
  /**
   * Posts GET handler
   *
   * Lists posts for a user. Optional parameters are `l` (limit of returned list),  `p` (page, i.e. offset), `s` (sort order).
   *
   * Returns list of posts.
   *
   * @throws 404 User not found
   */
  public function get($id): void
  {
    // Fetch and constrain all parameters.
    $page = max(0, intval(Input::get("p", 0)));
    $limit = constrain(0, 30, intval(Input::get("l", 10)));
    $sort = Input::get("s", "asc");
    $sort = in_array($sort, ["asc", "desc"]) ? $sort : "asc";

    // Try and get users posts
    // Throw errors according to situation.
    try {
      Response::json(User::getByID($id)->posts($page, $limit, $sort));
    } 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;
      }
    }
  }
}
