import { doInvalidateDrawing } 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";
import { AVATAR_ENTRY_PATH } from "@/app/www/utilities/Path";
import { writeFile } from "fs/promises";
import { join } from "path";

export const POST = logIP(
  validateMillis(
    validateTotem(async (req) => {
      const avatarID = req.headers.get("avatarID") as string;

      await writeFile(
        join(AVATAR_ENTRY_PATH, `${avatarID}.png`),
        Buffer.from(await req.arrayBuffer()),
      );
      await doInvalidateDrawing(avatarID);
      return new Response(undefined, { status: 201 });
    }),
  ),
);
