import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";
import validateTotem from "@/app/www/media/validateTotem";
import {
  doModifyEssay,
  getEssay,
  postEssay,
  wipeEssay,
} from "@/app/www/logic/essay";

export const GET = logIP(async (req, { params: { essayID } }) => {
  const language = req.nextUrl.searchParams.get("language");
  if (!language) {
    return new Response(undefined, { status: 400 });
  }

  const essay = await getEssay(
    Number(essayID),
    language as string,
    req.headers.get("X-Real-IP") as string,
  );
  if (essay) {
    return Response.json(essay);
  } else {
    return new Response(undefined, { status: 404 });
  }
});

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

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

      return new Response(undefined, {
        status: (await doModifyEssay(
          Number(essayID),
          avatarID,
          title,
          text,
          level,
        ))
          ? 204
          : 403,
      });
    }),
  ),
);

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

      return new Response(undefined, {
        status: (await wipeEssay(Number(essayID), avatarID, level)) ? 204 : 403,
      });
    }),
  ),
);

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

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

      const essayID = await postEssay(forumID, avatarID, level, title, text);
      if (essayID >= 0) {
        return Response.json({ essayID });
      } else {
        return new Response(undefined, { status: 403 });
      }
    }),
  ),
);
