import {
  doModifyAutoEssay,
  postAutoEssay,
  wipeAutoEssay,
} from "@/app/www/logic/autoEssay";
import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";
import validateTotem from "@/app/www/media/validateTotem";

export const POST = logIP(
  validateMillis(
    validateTotem(async (req, { params: { forumID } }) => {
      const avatarID = req.headers.get("avatarID");
      const { title, text } = await req.json();

      return Response.json(
        {
          autoEssayID: Number(
            await postAutoEssay(forumID, avatarID as string, title, text),
          ),
        },
        { status: 201 },
      );
    }),
  ),
);

export const PUT = logIP(
  validateMillis(
    validateTotem(async (req, { params: { autoEssayID } }) => {
      const avatarID = req.headers.get("avatarID");
      const { title, text } = await req.json();

      return new Response(undefined, {
        status: (await doModifyAutoEssay(
          Number(autoEssayID),
          avatarID as string,
          title,
          text,
        ))
          ? 204
          : 403,
      });
    }),
  ),
);

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

      return new Response(undefined, {
        status: (await wipeAutoEssay(Number(autoEssayID), avatarID))
          ? 204
          : 403,
      });
    }),
  ),
);
