const multer = require("multer");
const path = require("path");
const fs = require("fs"); // Use standard fs for mkdirSync

// --- 1. Define the directory path ---
// Based on your structure: backend/storage/middlewareStorage/uploadPartnerMedia.js
// We want to go to: backend/storage/storageMedia/partners
const uploadDir = path.join(__dirname, "../storageMedia/partners");

// --- 2. Ensure directory exists ---
// This prevents the ENOENT error by creating the folder if missing
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// --- 3. Multer Configuration ---
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, `partner-${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.uploadPartnerImage = upload.single("image");

// --- 4. Helper: Delete Old Image ---
const fsPromises = require("fs").promises; // Async fs for deletion

exports.deleteOldPartnerImage = async (imageName) => {
  if (!imageName) return;

  const filePath = path.join(uploadDir, imageName);

  try {
    await fsPromises.unlink(filePath);
  } catch (err) {
    // Ignore error if file doesn't exist
    // console.warn(`File not found or already deleted: ${imageName}`);
  }
};
