import sharp from "sharp";
import path from "path";
import fs from "fs";
import { getUploadPath, objectFilterEmpty } from "./library";

export const resizeImage = async ({
  filesPath = [],
  maxHeight = 500,
  maxWidth = 800,
  destinationPath = "",
}) => {
  if (Array.isArray(filesPath)) filesPath = [filesPath];
  filesPath = filesPath.filter((path) => path).flat();

  // define upload directory
  const uploadDir = destinationPath || getUploadPath().dir;

  const result = await Promise.all(
    filesPath.map(async (filepath, index) => {
      try {
        // get image size
        const { width, height } = await sharp(filepath).metadata();
        // define image size
        const size = {
          width: width > maxWidth ? maxWidth : null,
          height: height > maxHeight ? maxHeight : null,
        };

        // If no size is found, return null
        if (Object.values(size).every((size) => !size)) return null;

        const extension = path.extname(filepath);
        const tempPath = path.join(uploadDir, `temp-${index}${extension}`);

        // rename file to temp
        fs.renameSync(filepath, tempPath);

        const resizedFile = await sharp(tempPath)
          .resize({
            ...objectFilterEmpty(size), // remove null values
            fit: "cover",
            position: "centre",
          })
          .toFile(filepath); // save file to original path

        // delete temp file
        fs.unlinkSync(tempPath);

        return resizedFile;
      } catch (error) {
        return { error: error.message };
      }
    })
  );

  return result;
};
