<?php

// Namespaces

use Khofmann\ApiError\ApiError;
use Pecee\SimpleRouter\SimpleRouter;
use Pecee\Http\Request;
use Khofmann\Response\Response;

// Error handling
SimpleRouter::error(function (Request $request, Exception $exception) {
  $code = $exception->getCode();
  if ($exception instanceof ApiError) Response::apiError($exception->getMessage(), $code);
  else Response::response()->httpCode(is_int($code) ? $code : 500)->json(["message" => $exception->getMessage()]);
});

// CORS
SimpleRouter::options('/', function () {
  Response::response()
    ->header("Access-Control-Allow-Origin: *")
    ->header("Access-Control-Allow-Methods: *")
    ->header("Access-Control-Allow-Headers: *");
})->setMatch('/(.+)/is');

// Index
SimpleRouter::all("/", function () {
  Response::redirect("docs", 301);
});

/*
* Open
*/
// Login
SimpleRouter::post("/login", [Api\Login\Login::class, "post"]);
// Register and confirm
SimpleRouter::post("/register", [Api\Register\Register::class, "post"]);
SimpleRouter::patch("/register", [Api\Register\Register::class, "patch"]);

/*
* Optional Auth
*/
SimpleRouter::group(["middleware" => Khofmann\Auth\OptAuth::class], function () {
  // List posts
  SimpleRouter::get("/posts", [Api\Posts\Posts::class, "get"]);
});

/*
* Normal Auth
*/

SimpleRouter::group(["middleware" => Khofmann\Auth\Auth::class], function () {
  // Logout
  SimpleRouter::post("/logout", [Api\Logout\Logout::class, "post"]);
  // Get user
  SimpleRouter::get("/users/{id}", [Api\Users\Users::class, "get"]);
  // Get user posts
  SimpleRouter::get("/users/{id}/posts", [Api\Users\Posts\Posts::class, "get"]);
  // Update self
  SimpleRouter::patch("/users/self", [Api\Users\Users::class, "patchSelf"]);
  // Update image self
  SimpleRouter::post("/users/self/image", [Api\Users\Image\Image::class, "postSelf"]);
  // Update post
  SimpleRouter::patch("/posts/{id}", [Api\Posts\Posts::class, "patch"]);
  // Create post
  SimpleRouter::post("/posts", [Api\Posts\Posts::class, "post"]);
});

/*
* Admin Auth
*/

SimpleRouter::group(["middleware" => Khofmann\Auth\AdminAuth::class], function () {
  // List users
  SimpleRouter::get("/users", [Api\Users\Users::class, "list"]);
  // Update user
  SimpleRouter::patch("/users/{id}", [Api\Users\Users::class, "patch"]);
  // Update image
  SimpleRouter::post("/users/{id}/image", [Api\Users\Image\Image::class, "post"]);
  // Delete user
  SimpleRouter::delete("/users/{id}", [Api\Users\Users::class, "delete"]);
  // Delete post
  SimpleRouter::delete("/posts/{id}", [Api\Posts\Posts::class, "delete"]);
});
