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

export const GET = logIP(async () => {
  return new Response(DEFAULT_AVATAR_ASSET, {
    headers: {
      ["content-type"]: "image/png",
    },
  });
});

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

      const data = (await req.formData()).get("data");
      if (!data) {
        return new Response(undefined, { status: 400 });
      }

      const file = data as File;

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