import { doModifyAvatar, postAvatar } from "@/app/www/logic/avatar";
import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";
import validateTotem from "@/app/www/media/validateTotem";

export const PUT = logIP(
  validateMillis(
    validateTotem(async (req) => {
      const totem = req.headers.get("totem") as string;
      const avatarID = req.headers.get("avatarID") as string;
      const {
        avatarCipher,
        avatarCipherModified,
        avatarName,
        fax,
        avatarIntro,
      } = await req.json();

      if (
        !(await doModifyAvatar(
          totem,
          avatarID,
          avatarCipher,
          avatarCipherModified,
          avatarName,
          fax,
          avatarIntro,
        ))
      ) {
        return new Response(undefined, { status: 403 });
      }
      return Response.json({
        isAvatarCipherModified: !!avatarCipherModified,
      });
    }),
  ),
);

export const POST = logIP(
  validateMillis(async (req) => {
    const { avatarID, avatarCipher, avatarName, fax } = await req.json();

    return new Response(undefined, {
      status: (await postAvatar(avatarID, avatarCipher, avatarName, fax))
        ? 204
        : 403,
    });
  }),
);
