const path = require("path");

exports.uploadMissionImage = 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.Mission_IMAGE_PATH, fileName); // Include process.env.Mission_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.Mission_IMAGE_PATH}/${fileName}`; // Construct the relative file path

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

    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.
  }
};
