const admin = require("firebase-admin");
const db = admin.firestore();
const logger = require("firebase-functions/logger");
const auth = require("../utils/auth");
const helpers = require("../utils/helpers");

// Récupère toutes les alertes (filtrées et limitées)
exports.getAlerts = async (req, res) => {
  try {
    await auth.authenticateUser(req);

    const snapshot = await db.collection("alerts")
        .orderBy("createdAt", "desc")
        .limit(100)
        .get();

    const alerts = snapshot.docs.map((doc) => {
      const data = doc.data();
      return {
        id: doc.id,
        ...helpers.serializeTimestamps(data, ["createdAt"]),
      };
    });

    res.status(200).json({alerts});
  } catch (error) {
    logger.error("Error fetching alerts:", error);
    res.status(500).json({error: error.message});
  }
};

// Marquer une alerte comme lue
exports.markAlertAsRead = async (req, res) => {
  try {
    await auth.authenticateUser(req);

    const alertId = req.body.data?.alertId;
    if (!alertId) {
      res.status(400).json({error: "alertId is required"});
      return;
    }

    await db.collection("alerts").doc(alertId).update({
      isRead: true,
    });

    res.status(200).json({success: true});
  } catch (error) {
    logger.error("Error marking alert as read:", error);
    res.status(500).json({error: error.message});
  }
};

// Supprimer une alerte
exports.deleteAlert = async (req, res) => {
  try {
    await auth.authenticateUser(req);

    const alertId = req.body.data?.alertId;
    if (!alertId) {
      res.status(400).json({error: "alertId is required"});
      return;
    }

    await db.collection("alerts").doc(alertId).delete();

    res.status(200).json({success: true});
  } catch (error) {
    logger.error("Error deleting alert:", error);
    res.status(500).json({error: error.message});
  }
};
