import fs from "fs";
import path from "path";
import { resizeImage } from "@/utils/resize.file";
import { getUploadPath, spliceObject } from "./library";

export const uploadFile = async (
  request,
  option = { destinationPath: "", resize: true }
) => {
  const { destinationPath, resize } = option;
  const mimetypeAllowed = [
    "image/png",
    "image/jpeg",
    "image/jpg",
    "image/webp",
    "image/gif",
  ];
  const uploadDir = destinationPath || getUploadPath().dir;

  // get files from form data, whatever name of input
  const formData = await request.formData();
  const keys = Object.keys(Object.fromEntries(formData));
  const filesData = keys
    .map((key) => formData.getAll(key))
    .flat()
    .filter((file) => file instanceof File); // only files

  // filter files
  const files = filesData.filter((file) => mimetypeAllowed.includes(file.type));

  const result = await Promise.all(
    files.map(async (file) => {
      const fileName = Date.now() + "-" + file.name.replace(/\s/g, "-");
      const filepath = path.join(uploadDir, fileName);

      const buffer = await file.arrayBuffer();
      fs.writeFileSync(filepath, Buffer.from(buffer));

      return {
        name: file.name.split(".")[0],
        filename: fileName,
        url: (() => {
          const _path = path.resolve(filepath).split(path.sep);
          const publicIndex = _path.findIndex((path) => path === "public");

          _path.splice(0, publicIndex + 1);

          return ["", ..._path].join("/");
        })(),
        path: filepath,
        size: file.size,
      };
    })
  );

  // resizing image, if needed
  if (resize) {
    const _ = await resizeImage({
      filesPath: result.map((file) => file.path),
      destinationPath: uploadDir,
    });
  }

  return {
    ...spliceObject(Object.fromEntries(formData), ["file"]).spliced,
    files: result.map((file) => ({
      ...file,
      success: fs.existsSync(file.path),
    })),
  };
};
