import Router from "koa-router";
import { validateMillis } from "src/mws/millis";
import {
  doModifyCommentary,
  getCommentary,
  postCommentary,
  wipeCommentary,
} from "src/systems/commentary";

const router = new Router();

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

router.post("/", validateMillis, async (ctx) => {
  const {
    request: {
      ip,
      body: { avatarName, avatarCipher, text },
    },
  } = ctx;

  if (await postCommentary(avatarName, avatarCipher, ip, text)) {
    ctx.status = 201;
  } else {
    ctx.status = 403;
  }
});

router.put("/", validateMillis, async (ctx) => {
  const {
    request: {
      body: { commentaryID, avatarCipher, text },
    },
  } = ctx;

  if (await doModifyCommentary(commentaryID, avatarCipher, text)) {
    ctx.status = 204;
  } else {
    ctx.status = 403;
  }
});

router.delete("/", validateMillis, async (ctx) => {
  const {
    query: { commentaryID, avatarCipher },
  } = ctx;

  if (await wipeCommentary(Number(commentaryID), avatarCipher as string)) {
    ctx.status = 204;
  } else {
    ctx.status = 403;
  }
});

export default router;
