const path = require("path");

exports.uploadPostImage = async (file, req) => {
  const originalFileName = file.name;
  const fileNameWithoutSpaces = originalFileName.replace(/\s+/g, ""); // Remove spaces from the file name
  const fileName = `${Math.floor(Math.random() * 100000 + 1)}_${fileNameWithoutSpaces}`;
  const filePath = path.join(process.env.POST_IMAGE_PATH, fileName); // Include process.env.POST_IMAGE_PATH in the file path

  try {
    await file.mv(filePath);

    const relativeFilePath = `${process.env.POST_IMAGE_PATH}/${fileName}`; // Construct the relative file path

    const fileURL = relativeFilePath.replace(/^\.\//, '/'); // Remove the leading dot if it exists

    console.log("Image path:", fileURL);
    console.log("before:", relativeFilePath);
    return fileURL;
  } catch (err) {
    console.error("Error uploading file:", err);
    throw err; // Re-throw the error to handle it elsewhere, e.g., in the controller.
  }
};
