import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";
import validateTotem from "@/app/www/media/validateTotem";
import {
  doModifyComment,
  getComments,
  postComment,
  wipeComment,
} from "@/app/www/logic/comment";

export const GET = logIP(async (req, { params: { commentID: essayID } }) => {
  return Response.json(await getComments(Number(essayID)));
});

export const POST = logIP(
  validateMillis(
    validateTotem(async (req, { params: { commentID: essayID } }) => {
      const { targetCommentID, text } = await req.json();
      if (!targetCommentID || !text) {
        return new Response(undefined, { status: 400 });
      }

      const avatarID = req.headers.get("avatarID") as string;
      const level = Number(req.headers.get("level") as string);

      return new Response(undefined, {
        status: (await postComment(
          Number(targetCommentID),
          Number(essayID),
          avatarID,
          level,
          text,
        ))
          ? 201
          : 403,
      });
    }),
  ),
);

export const PUT = logIP(
  validateMillis(
    validateTotem(async (req, { params: { commentID } }) => {
      const avatarID = req.headers.get("avatarID") as string;
      const level = Number(req.headers.get("level") as string);

      const { text } = await req.json();
      if (!text) {
        return new Response(undefined, { status: 400 });
      }

      return new Response(undefined, {
        status: (await doModifyComment(
          Number(commentID),
          avatarID as string,
          text,
          Number(level),
        ))
          ? 204
          : 403,
      });
    }),
  ),
);

export const DELETE = logIP(
  validateMillis(
    validateTotem(async (req, { params: { commentID } }) => {
      const avatarID = req.headers.get("avatarID") as string;
      const level = Number(req.headers.get("level") as string);

      return new Response(undefined, {
        status: (await wipeComment(
          Number(commentID),
          avatarID as string,
          level,
        ))
          ? 204
          : 403,
      });
    }),
  ),
);
