const multer = require("multer");
const path = require("path");
const fs = require("fs");

// --- Configuration ---
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    let uploadPath = "";

    // Determine folder based on file type
    if (file.mimetype.startsWith("image")) {
      // Resolved Path: storage/storageMedia/campus/images
      uploadPath = path.join(__dirname, "../storageMedia/campus/images");
    } else if (file.mimetype.startsWith("video")) {
      // Resolved Path: storage/storageMedia/campus/videos
      uploadPath = path.join(__dirname, "../storageMedia/campus/videos");
    } else {
      return cb(new Error("Invalid file type! Only images or videos."), false);
    }

    // ✅ FIX: Ensure directory exists automatically to prevent ENOENT errors
    fs.mkdir(uploadPath, { recursive: true }, (err) => {
      if (err) return cb(err, false);
      cb(null, uploadPath);
    });
  },
  filename: (req, file, cb) => {
    // Generate a clean extension
    const ext =
      path.extname(file.originalname) || `.${file.mimetype.split("/")[1]}`;

    // Unique filename: campus-{timestamp}-{random}.{ext}
    const uniqueSuffix = `campus-${Date.now()}-${Math.round(
      Math.random() * 1e9
    )}${ext}`;
    cb(null, uniqueSuffix);
  },
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image") || file.mimetype.startsWith("video")) {
    cb(null, true);
  } else {
    cb(new Error("Not an image or video!"), false);
  }
};

const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 100 * 1024 * 1024 }, // 100MB limit for videos
});

// --- Export Middleware for Multiple Fields ---
exports.uploadCampusMedia = upload.fields([
  { name: "coverImage", maxCount: 1 },
  { name: "promoVideo", maxCount: 1 },
  { name: "images", maxCount: 10 },
]);
