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

// --- Multer Storage Configuration ---
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Ensure this path matches your directory structure
    cb(null, path.join(__dirname, "../storageMedia/users"));
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split("/")[1];

    // 🔥 CRITICAL FIX: Handle case where req.user is undefined (Signup)
    // If logged in, use ID. If signing up, use 'new-timestamp'.
    const userId = req.user ? req.user.id : `new-${Date.now()}`;

    const fileName = `user-${userId}-${Date.now()}.${ext}`;
    cb(null, fileName);
  },
});

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
});

// Helper to delete old photos
const deleteOldPhoto = async (photoName) => {
  if (!photoName) return;
  const isDefault = photoName.startsWith("default");
  if (!isDefault) {
    const filePath = path.join(__dirname, "../storageMedia/users", photoName);
    try {
      await fs.unlink(filePath);
    } catch (err) {
      console.warn(`File not found: ${photoName}`);
    }
  }
};

// NEW: Middleware to handle base64 images
const handleBase64Image = async (req, res, next) => {
  try {
    // Check if photo is base64 string
    if (req.body.photo && req.body.photo.startsWith("data:image")) {
      const matches = req.body.photo.match(
        /^data:image\/([a-zA-Z]+);base64,(.+)$/,
      );

      if (!matches || matches.length !== 3) {
        return next(new Error("Invalid base64 image format"));
      }

      const ext = matches[1]; // jpeg, png, etc.
      const base64Data = matches[2];
      const buffer = Buffer.from(base64Data, "base64");

      // 🔥 CRITICAL FIX: Handle case where req.user is undefined (Signup)
      const userId = req.user ? req.user.id : `new-${Date.now()}`;

      // Generate filename
      const fileName = `user-${userId}-${Date.now()}.${ext}`;
      const filePath = path.join(__dirname, "../storageMedia/users", fileName);

      // Save file
      await fs.writeFile(filePath, buffer);

      // Set filename in request so controller can save it to DB
      req.file = { filename: fileName };
      req.body.photo = fileName;
    }

    next();
  } catch (error) {
    next(error);
  }
};

module.exports = {
  uploadUserPhoto: upload.single("photo"),
  handleBase64Image,
  deleteOldPhoto,
};
