import { initializeApp, type FirebaseApp } from "firebase/app";
import { getMessaging, getToken, type Messaging } from "firebase/messaging";
import { VAPI_PUBLIC_KEY } from "./constants";
import { firebaseConfig } from "./firebase";

const firebase: {
  app: FirebaseApp | null,
  messaging: Messaging | null,
  registeration: ServiceWorkerRegistration | null,
} = {
  app: null,
  messaging: null,
  registeration: null,
};

// Initialize Firebase
export const getFirebaseApp = () => {
  if (!firebase.app) {
    firebase.app = initializeApp(firebaseConfig);
  }
  return firebase.app;
};
// getAnalytics(app);

export const initServiceWorker = async () => {
  if (!firebase.registeration) {
    firebase.registeration = await navigator.serviceWorker.register('/sw.js', {
      scope: '/',
    });
  }
  console.debug('Serviceworker inited', firebase);
  return firebase.registeration;
}

export const getFirebaseMessaging = () => {
  if (!firebase.messaging) {
    firebase.messaging = getMessaging(getFirebaseApp());
  }
  return firebase.messaging;
};

export async function getFirebaseToken() {
  const registeration = await initServiceWorker(); 
  await registeration.update();
  const token = await getToken(getFirebaseMessaging(), { 
    vapidKey: VAPI_PUBLIC_KEY,
    serviceWorkerRegistration: registeration,
  });
  return token;
}