import {
  doModifyCommentary,
  getCommentary,
  postCommentary,
  wipeCommentary,
} from "@/app/www/logic/commentary";
import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";

export const GET = logIP(async () => {
  return Response.json(await getCommentary());
});

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

    return new Response(undefined, {
      status: (await postCommentary(
        avatarName,
        avatarCipher,
        req.headers.get("X-Real-IP") as string,
        text,
      ))
        ? 201
        : 403,
    });
  }),
);

export const PUT = logIP(
  validateMillis(async (req) => {
    const { commentaryID, avatarCipher, text } = await req.json();
    if (!commentaryID || !avatarCipher || !text) {
      return new Response(undefined, { status: 400 });
    }

    return new Response(undefined, {
      status: (await doModifyCommentary(commentaryID, avatarCipher, text))
        ? 201
        : 403,
    });
  }),
);

export const DELETE = logIP(
  validateMillis(async ({ nextUrl: { searchParams } }) => {
    const avatarCipher = searchParams.get("avatarCipher");
    const commentaryID = searchParams.get("commentaryID");

    if (!avatarCipher || !commentaryID) {
      return new Response(undefined, { status: 400 });
    }

    return new Response(undefined, {
      status: (await wipeCommentary(Number(commentaryID), avatarCipher))
        ? 204
        : 403,
    });
  }),
);
