import messaging, { getMessaging, getToken } from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { getApp } from '@react-native-firebase/app';



async function requestUserPermission(os) {
  const authStatus = await messaging().requestPermission();
  console.log("authStatus",authStatus)
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled) {
    const token = await getFcmToken(os);
    console.log(token, ' token ....firebase');
    return token;
  }
}

const getFcmToken = async os => {
  let checkToken = await AsyncStorage.getItem('fcmToken');
  if (!checkToken) {
    try {
      // const fcmToken = await messaging().getToken();
      const app = getApp(); 
      const messagingInstance = getMessaging(app); // ✅ Use the modular API
      const fcmToken = await getToken(messagingInstance);
      if (!!fcmToken) {
        await AsyncStorage.setItem(
          'fcmToken',
          JSON?.stringify({fcmToken, PlatformOs: os}),
        );
        return JSON?.stringify({fcmToken, PlatformOs: os});
      }
    } catch (error) {
      console.log('error in fcmToken', error);
    }
  } else {
    return checkToken;
  }
};

export default requestUserPermission;
