// src/firebase/notification.js
import { getToken, onMessage } from "firebase/messaging";
import { messaging } from "./firebase"; // initialized messaging
import { dispatch } from "store";
import { setFcmToken } from "../store/reducers/fcmSlice";
import { setFcmPermission } from "store/reducers/fcmSlice";
// generate token when webpage is open and sent this to backend via login api,

export const generateToken = async () => {
  try {
    const permission = await Notification.requestPermission();
    console.log("Permission", permission);
    dispatch(setFcmPermission(permission));
    if (permission !== "granted") {
      console.log("Permission not granted for notifications");
      return;
    }

    const token = await getToken(messaging, {
      // vapidKey: process.env.REACT_APP_FIREBASE_VAPID_KEY
      vapidKey:
        "BBfin2w2LLwc51gmgIUzSi9F6C6TchC99xwIWVpodbZJckqhyuN_2BKmIaA7cwF2JiqhzYJ0Rqszjh1-pDgYMWw",
    });

    if (token) {
      console.log("📌 Token generated:", token);
      dispatch(setFcmToken(token)); // Make sure Redux is ready
    } else {
      console.warn("No registration token available.");
    }
  } catch (err) {
    console.error("❌ Error fetching FCM token:", err.message);
  }
};
// foreground notifications
export const initFirebaseNotificationListener = () => {
  onMessage(messaging, (payload) => {
    console.log("📥 Foreground message received:", payload.notification);

    // You can show a system notification:
    new Notification(payload.notification.title, {
      body: payload.notification.body,
      icon: payload.notification.image || "/favicon.ico",
    });

    // OR update Redux store/UI here if needed
  });
};
