// middleware/firebaseAuth.js
import admin from "firebase-admin";

// Initialize Firebase Admin SDK
if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n"),
    }),
  });
}

export default async function firebaseAuth(req, res, next) {
  const token = req.headers.authorization?.split(" ")[1]; // Bearer <ID_TOKEN>

  if (!token) {
    return res.status(401).json({ ok: false, message: "Unauthorized" });
  }

  try {
    const decoded = await admin.auth().verifyIdToken(token);
    req.user = {
      uid: decoded.uid,
      name: decoded.name || "",
      avatar: decoded.picture || "",
      email: decoded.email || "",
    };
    next();  // pass control to the next handler
  } catch (err) {
    return res.status(401).json({ ok: false, message: "Invalid token" });
  }
}
