import { initializeApp } from 'firebase/app';
import { getMessaging, onMessage, isSupported } from 'firebase/messaging';

export const firebaseConfig = {
  apiKey: "AIzaSyDBDwlnQsbIxKni_UzZxDjeIk0akK-vDPM",
  authDomain: "health-apps-69256.firebaseapp.com",
  projectId: "health-apps-69256",
  storageBucket: "health-apps-69256.firebasestorage.app",
  messagingSenderId: "257956159594",
  appId: "1:257956159594:web:2e66b8d4d37e2382c76a13",
};

const firebaseApp = initializeApp(firebaseConfig);
export default firebaseApp;

// Initialize messaging only if supported
let messagingInstance = null;

// Check if messaging is supported before initializing
export const initializeMessaging = async () => {
  try {
    const isSupportedBrowser = await isSupported();
    if (isSupportedBrowser) {
      messagingInstance = getMessaging(firebaseApp);
      return messagingInstance;
    } else {
      console.log('Firebase messaging is not supported in this browser');
      return null;
    }
  } catch (error) {
    console.error('Error checking messaging support:', error);
    return null;
  }
};

// Safe getter for messaging
export const getMessagingInstance = () => messagingInstance;

// Safe onForegroundMessage function
export const onForegroundMessage = async () => {
  const messaging = await initializeMessaging();
  if (!messaging) {
    return Promise.resolve(null); // Return resolved promise with null if messaging not supported
  }
  return new Promise((resolve) => onMessage(messaging, (payload) => resolve(payload)));
};
