import AsyncStorage from '@react-native-async-storage/async-storage';
import messaging from '@react-native-firebase/messaging';

const TOPIC = 'new-conferences';
const KEY = 'notifications:enabled';

export async function isEnabled(): Promise<boolean> {
  return (await AsyncStorage.getItem(KEY)) === '1';
}

// Opt-in only: asks for OS permission, then subscribes the device to the topic.
// No token is sent to our servers; FCM keeps the subscription.
export async function setEnabled(on: boolean): Promise<boolean> {
  if (on) {
    const status = await messaging().requestPermission();
    const ok =
      status === messaging.AuthorizationStatus.AUTHORIZED ||
      status === messaging.AuthorizationStatus.PROVISIONAL;
    if (!ok) return false;
    await messaging().subscribeToTopic(TOPIC);
  } else {
    await messaging().unsubscribeFromTopic(TOPIC);
  }
  await AsyncStorage.setItem(KEY, on ? '1' : '0');
  return on;
}
