const { setGlobalOptions } = require("firebase-functions");
const { onValueCreated } = require("firebase-functions/v2/database");
const admin = require("firebase-admin");

admin.initializeApp();

setGlobalOptions({ maxInstances: 10 });

/// 🔔 1. NOTIFIKASI TRIGGER (MONITORING & SELESAI)
exports.notifHandler = onValueCreated(
  "/notifikasi/{id}",
  async (event) => {
    try {
      const data = event.data.val();
      if (!data) return null;

      const tipe = data.tipe || "";
      const jenisTape = data.jenisTape || "Ketan";
      const waktu = data.waktu || "-";
      const suhu = data.suhu || "-";
      const alkohol = data.alkohol || "-";
      const status = data.status || "";
      const jamTotal = data.jam_total || data.waktu || "-";

      /// AMBIL TOKEN
      const tokenSnap = await admin.database().ref("fcm_token").once("value");
      const token = tokenSnap.val();

      if (!token) {
        console.log("❌ Token tidak ada");
        return null;
      }

      let message;

      if (tipe === "monitoring") {
        const delta = data.delta_alkohol !== undefined ? data.delta_alkohol : "-";
        message = {
          notification: {
            title: `📊 Monitoring Tape ${jenisTape}`,
            body: `Status: ${status}\nSuhu: ${suhu}°C\nAlkohol: ${alkohol}%\nDelta 3 Jam: ${delta}%`,
          },
          token: token,
        };
      } else if (tipe === "selesai") {
        message = {
          notification: {
            title: `🍌 Fermentasi Tape ${jenisTape} Selesai!`,
            body: `Waktu: ${waktu}\nTotal Waktu: ${jamTotal} Jam\nSuhu: ${suhu}°C\nAlkohol: ${alkohol}%\nStatus: ${status}`,
          },
          token: token,
        };
      } else {
        console.log(`⚠️ Tipe notifikasi tidak dikenal: ${tipe}`);
        return null;
      }

      await admin.messaging().send(message);
      console.log(`✅ Notif ${tipe} terkirim`);
      return null;
    } catch (error) {
      console.error("❌ Error sending notification:", error);
      return null;
    }
  }
);

/// 🔔 2. PERINGATAN TRIGGER (HANYA TERLALU MATANG)
exports.peringatanHandler = onValueCreated(
  "/peringatan/{id}",
  async (event) => {
    try {
      const data = event.data.val();
      if (!data) return null;

      const status = data.status || "";
      const jenisTape = data.jenisTape || "Ketan";
      const suhu = data.suhu || "-";
      const alkohol = data.alkohol || "-";
      const waktu = data.waktu || "-";

      // HANYA kirim jika status "Terlalu Matang"
      if (status !== "Terlalu Matang") {
        console.log(`⚠️ Mengabaikan peringatan dengan status: ${status}`);
        return null;
      }

      /// AMBIL TOKEN
      const tokenSnap = await admin.database().ref("fcm_token").once("value");
      const token = tokenSnap.val();

      if (!token) {
        console.log("❌ Token tidak ada");
        return null;
      }

      const message = {
        notification: {
          title: `⚠️ Peringatan: Tape ${jenisTape} Terlalu Matang!`,
          body: `Tape sudah terlalu matang.\nWaktu: ${waktu}\nSuhu: ${suhu}°C\nAlkohol: ${alkohol}%`,
        },
        token: token,
      };

      await admin.messaging().send(message);
      console.log("✅ Notif peringatan Terlalu Matang terkirim");
      return null;
    } catch (error) {
      console.error("❌ Error sending warning notification:", error);
      return null;
    }
  }
);