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 Configuration ---
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Correct Path: storage/middlewareStorage/../storageMedia/categories
    // Resolves to: storage/storageMedia/categories
    const uploadPath = path.join(__dirname, "../storageMedia/categories");

    // ✅ FIX: Create directory if it doesn't exist to prevent ENOENT
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }

    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    // Unique filename: category-{timestamp}-{random}.ext
    const uniqueSuffix = `category-${Date.now()}-${Math.round(
      Math.random() * 1e9
    )}${ext}`;
    cb(null, uniqueSuffix);
  },
});

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.uploadCategoryIcon = upload.single("icon");

// --- 2. Helper: Delete Old Icon ---
exports.deleteOldCategoryIcon = async (iconName) => {
  if (!iconName) return;
  if (iconName.startsWith("default")) return;

  // ✅ FIX: Correct path to delete
  const filePath = path.join(__dirname, "../storageMedia/categories", iconName);

  try {
    await fsPromises.unlink(filePath);
  } catch (err) {
    // Gracefully handle missing files
    console.warn(
      `[Warning] Could not delete old category icon: ${iconName} (${err.code})`
    );
  }
};
