import logIP from "@/app/www/media/logIP";
import validateMillis from "@/app/www/media/validateMillis";
import validateTotem from "@/app/www/media/validateTotem";
import { ESSAY_ENTRY_PATH } from "@/app/www/utilities/Path";
import { writeFile } from "fs/promises";
import { join, parse } from "path";
import { v4 } from "uuid";

export const POST = logIP(
  validateMillis(
    validateTotem(async (req) => {
      const data = (await req.formData()).get("data");
      if (!data) {
        return new Response(undefined, { status: 400 });
      }

      const file = data as File;
      const { name } = file;
      const { ext } = parse(name);
      const fileName = v4() + ext;

      await writeFile(
        join(ESSAY_ENTRY_PATH, fileName),
        Buffer.from(await file.arrayBuffer()),
        { flag: "w" },
      );
      return Response.json({ fileName }, { status: 201 });
    }),
  ),
);
