const multer = require("multer");
const path = require("path");
const fs = require("fs"); // Use standard fs for mkdirSync
const fsPromises = require("fs").promises; // Use promises for unlink

// --- 1. Multer Config ---
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // ✅ FIX 1: Adjusted Path
    // Current file is in: .../storage/middlewareStorage/
    // We want to go to:   .../storage/storageMedia/staff/
    // So we go UP one level (..) to 'storage', then down to 'storageMedia'
    const uploadPath = path.join(__dirname, "../storageMedia/staff");

    // ✅ FIX 2: Auto-create directory if it doesn't exist
    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 = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, `staff-${uniqueSuffix}${ext}`);
  },
});

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,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
});

exports.uploadStaffPhoto = upload.single("photo");

// --- 2. Helper: Delete Old Photo ---
exports.deleteOldStaffPhoto = async (photoName) => {
  if (!photoName) return;
  // Don't delete default images
  if (photoName.startsWith("default")) return;

  // ✅ FIX 3: Adjusted Path here as well to match
  const filePath = path.join(__dirname, "../storageMedia/staff", photoName);

  try {
    await fsPromises.unlink(filePath);
  } catch (err) {
    // It's okay if file isn't found, just log a warning
    // console.warn(`File not found or already deleted: ${photoName}`);
  }
};
