import { FIREBASE_API } from "@/config-global";
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

const firebaseConfig = {
    apiKey: FIREBASE_API.apiKey,
    authDomain: FIREBASE_API.authDomain,
    projectId: FIREBASE_API.projectId,
    storageBucket: FIREBASE_API.storageBucket,
    messagingSenderId: FIREBASE_API.messagingSenderId,
    appId: FIREBASE_API.appId,
    measurementId: FIREBASE_API.measurementId
};

let firebaseApp;
let messaging: any;

if (typeof window !== 'undefined') {
    // Ensure Firebase is initialized only on the client side
    firebaseApp = initializeApp(firebaseConfig);
    messaging = getMessaging(firebaseApp);
}

export const generateToken = async () => {
    if (typeof window !== 'undefined') {
        const permission = await Notification.requestPermission();
    
        if (permission === "granted") {
            try {
                const token = await getToken(messaging, {
                    vapidKey: FIREBASE_API.vapiKey
                });
                return token;
                
            } catch (error) {
                console.error("An error occurred while retrieving token:", error);
            }
        } else {
            console.warn("Notification permission not granted");
        }
    }
    return null;
};

export { firebaseApp, messaging };
