const multer = require("multer");
const path = require("path");
const fs = require("fs"); // 1. Import the Node.js File System module

// 2. Define a more specific and robust path for logo uploads
const uploadDir = path.join(__dirname, "..", "assets", "logos");

// 3. (THE CORE FIX) - Check if the directory exists, and create it if it doesn't.
// This code runs once when your server starts.
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
  console.log(`Successfully created upload directory: ${uploadDir}`);
}

// Configure how files are stored
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 4. Point to the specific 'logos' subdirectory which is now guaranteed to exist.
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 5. (THE LOGIC FIX) - Use req.user.institution_id from the auth token, NOT req.params.id
    const institutionId = req.user.institution_id;
    if (!institutionId) {
      // This is a safeguard in case the user isn't properly authenticated
      return cb(new Error("User not associated with an institution."));
    }

    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    const newFilename = `logo-${institutionId}-${uniqueSuffix}${path.extname(
      file.originalname
    )}`;
    cb(null, newFilename);
  },
});

// Filter to allow only image files (your code for this is good)
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("Not an image! Please upload only images."), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 2, // Limit file size to 2MB
  },
});

module.exports = upload;
