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")) {
      // ✅ FIX: Use '../' to stay inside the 'storage' folder
      uploadPath = path.join(__dirname, "../storageMedia/courses/images");
    } else if (file.mimetype.startsWith("video")) {
      // ✅ FIX: Use '../' to stay inside the 'storage' folder
      uploadPath = path.join(__dirname, "../storageMedia/courses/videos");
    } else {
      return cb(
        new Error("Invalid file type. Only images and videos are allowed."),
        false
      );
    }

    // Ensure directory exists (Recursive creates parent folders if missing)
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }

    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const uniqueSuffix = `course-${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: 500 * 1024 * 1024 }, // 500MB
});

exports.uploadCourseMedia = upload.fields([
  { name: "coverImage", maxCount: 1 },
  { name: "promoVideo", maxCount: 1 },
  { name: "images", maxCount: 10 },
  { name: "certificateTemplate", maxCount: 1 },
]);
