import Router from "koa-router";
import { validateTotem } from "src/mws/avatar";
import { validateMillis } from "src/mws/millis";
import {
  doModifyAutoEssay,
  getAutoEssays,
  postAutoEssay,
  wipeAutoEssay,
} from "src/systems/autoEssay";

const router = new Router();

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

  ctx.body = {
    autoEssayID: Number(
      await postAutoEssay(forumID, avatarID as string, title, text),
    ),
  };
  ctx.status = 201;
});

router.get("/:forumID", validateTotem(false), async (ctx) => {
  const {
    params: { forumID },
    headers: { avatarID },
  } = ctx;

  const autoEssays = await getAutoEssays(forumID, avatarID as string);

  if (autoEssays) {
    ctx.body = autoEssays;
    ctx.status = 200;
  } else {
    ctx.status = 404;
  }
});

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

    if (
      await doModifyAutoEssay(
        Number(autoEssayID),
        avatarID as string,
        title,
        text,
      )
    ) {
      ctx.status = 204;
    } else {
      ctx.status = 403;
    }
  },
);

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

    if (await wipeAutoEssay(Number(autoEssayID), avatarID as string)) {
      ctx.status = 204;
    } else {
      ctx.status = 403;
    }
  },
);

export default router;
