const path = require("path");

exports.uploadsImage = 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.FILE_UPLOAD_PATH, fileName); // Include process.env.POST_IMAGE_PATH in the file path

  try {
    await file.mv(filePath);

    const protocol = req.protocol; // Get the protocol (http or https)
    const host = req.get("host"); // Get the host name and port (e.g., localhost:5000)
    const relativeFilePath = `${process.env.FILE_UPLOAD_PATH}/${fileName}`; // Construct the relative file path

    const fileURL = `${protocol}://${host}/${relativeFilePath}`; // Construct the full file URL

    console.log("Image path:", fileURL);
    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.
  }
};
