import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

const firebaseConfig = {
    apiKey: "AIzaSyBcoY_1ajskqS2TsSqsc-YI8RRtek_h3eY",
    authDomain: "newline-691b4.firebaseapp.com",
    projectId: "newline-691b4",
    storageBucket: "newline-691b4.firebasestorage.app",
    messagingSenderId: "509141563045",
    appId: "1:509141563045:web:4401a378be720ee0893f4c",
    measurementId: "G-YHTZBEVDKR"
};

const app = initializeApp(firebaseConfig);

export const messaging = getMessaging(app);

let tokenGenerated = false;

export const generateToken = async () => {
    try {

        const existingToken = localStorage.getItem("fcm_token");

        if (tokenGenerated && existingToken) {
            return existingToken;
        }

        tokenGenerated = true;

        console.log("generateToken called");

        const permission = await Notification.requestPermission();

        if (permission !== "granted") {
            return null;
        }

        const token = await getToken(messaging, {
            vapidKey: "BO4ZDBqG7pNGg2cvOCXPTi8TGIhuPWPiO33W9dUrsi5-4qwuCGMRweiqWFZfqHYh5liu4E3NcKu1xViSiJwEQjk"
        });

        if (token) {
            localStorage.setItem("fcm_token", token);
            console.log("FCM Token:", token);
        }

        return token;

    } catch (error) {
        console.error("FCM Error:", error);
        return null;
    }
};