const multer = require("multer");
const bucket = require("../utils/firebase");

// Multer memory storage
const storage = multer.memoryStorage();

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB limit
  fileFilter: (req, file, cb) => {
    if (file.mimetype !== "application/pdf") {
      return cb(new Error("Only PDF files are allowed"));
    }
    cb(null, true);
  },
});

// Firebase upload middleware
const firebaseUploadMiddleware = async (req, res, next) => {
  if (!req.file) return next();

  try {
    const folder = req.uploadFolder || "uploads"; // optional folder
    const fileName = `${folder}/${Date.now()}_${req.file.originalname}`;

    const file = bucket.file(fileName);

    const stream = file.createWriteStream({
      metadata: { contentType: req.file.mimetype },
    });

    stream.on("error", (err) => {
      console.error("Firebase Upload Middleware Error:", err);
      return res.status(500).json({ message: "Upload failed", error: err.message });
    });

    stream.on("finish", async () => {
      await file.makePublic(); // for testing; later use signed URLs if needed
      req.fileUrl = `https://storage.googleapis.com/${bucket.name}/${fileName}`;
      next();
    });

    stream.end(req.file.buffer);
  } catch (err) {
    console.error("Firebase Upload Middleware Error:", err);
    return res.status(500).json({ message: "Firebase upload error", error: err.message });
  }
};

module.exports = { upload, firebaseUploadMiddleware };
