import Router from "koa-router";
import { validateTotem } from "src/mws/avatar";
import { validateMillis } from "src/mws/millis";
import {
  doModifyComment,
  getComments,
  getLatestComments,
  postComment,
  wipeComment,
} from "src/systems/comment";

const router = new Router();

router.get("/latest", async (ctx) => {
  ctx.body = await getLatestComments();
  ctx.status = 200;
});

router.get("/:essayID", async (ctx) => {
  const {
    params: { essayID },
  } = ctx;

  ctx.body = await getComments(Number(essayID));
  ctx.status = 200;
});

router.post("/:essayID", validateMillis, validateTotem(false), async (ctx) => {
  const {
    params: { essayID },
    headers: { avatarID, level },
    request: {
      body: { targetCommentID, text },
    },
  } = ctx;

  if (
    await postComment(
      Number(targetCommentID),
      Number(essayID),
      avatarID as string,
      Number(level),
      text,
    )
  ) {
    ctx.status = 201;
  } else {
    ctx.status = 403;
  }
});

router.put("/:commentID", validateMillis, validateTotem(false), async (ctx) => {
  const {
    params: { commentID },
    headers: { avatarID, level },
    request: {
      body: { text },
    },
  } = ctx;

  if (
    await doModifyComment(
      Number(commentID),
      avatarID as string,
      text,
      Number(level),
    )
  ) {
    ctx.status = 204;
  } else {
    ctx.status = 403;
  }
});

router.delete(
  "/:commentID",
  validateMillis,
  validateTotem(false),
  async (ctx) => {
    const {
      params: { commentID },
      headers: { avatarID, level },
    } = ctx;

    if (
      await wipeComment(Number(commentID), avatarID as string, Number(level))
    ) {
      ctx.status = 204;
    } else {
      ctx.status = 403;
    }
  },
);

export default router;
