/**
 * 通知相关本地偏好（推送开关、提示音、震动）
 * 启动时 loadNotificationPreferences 会同步到内存，供 SSE / 系统通知 / Handler 读取
 */

import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Notifications from 'expo-notifications';
import { setVibrationEnabled } from './messageVibrationService';

export const NOTIFICATION_PREF_KEYS = {
  /** 与历史版本保持一致 */
  vibration: 'vibration_enabled',
  push: 'notification_push_enabled',
  sound: 'notification_sound_enabled',
} as const;

export type NotificationPrefs = {
  pushEnabled: boolean;
  soundEnabled: boolean;
  vibrationEnabled: boolean;
};

const defaults: NotificationPrefs = {
  pushEnabled: true,
  soundEnabled: true,
  vibrationEnabled: true,
};

let cached: NotificationPrefs = { ...defaults };

export function getNotificationPreferencesSync(): NotificationPrefs {
  return { ...cached };
}

function parseBool(raw: string | null, fallback: boolean): boolean {
  if (raw === null) return fallback;
  try {
    return JSON.parse(raw) as boolean;
  } catch {
    return fallback;
  }
}

/** 应用启动时调用：从 AsyncStorage 恢复并写入震动服务内存态 */
export async function loadNotificationPreferences(): Promise<NotificationPrefs> {
  try {
    const [vibrationRaw, pushRaw, soundRaw] = await Promise.all([
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.vibration),
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.push),
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.sound),
    ]);
    cached = {
      vibrationEnabled: parseBool(vibrationRaw, defaults.vibrationEnabled),
      pushEnabled: parseBool(pushRaw, defaults.pushEnabled),
      soundEnabled: parseBool(soundRaw, defaults.soundEnabled),
    };
    setVibrationEnabled(cached.vibrationEnabled);
    return { ...cached };
  } catch {
    return { ...cached };
  }
}

export async function setVibrationPreference(enabled: boolean): Promise<void> {
  cached.vibrationEnabled = enabled;
  setVibrationEnabled(enabled);
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.vibration, JSON.stringify(enabled));
}

export async function setPushNotificationsPreference(enabled: boolean): Promise<void> {
  cached.pushEnabled = enabled;
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.push, JSON.stringify(enabled));
}

export async function setSoundPreference(enabled: boolean): Promise<void> {
  cached.soundEnabled = enabled;
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.sound, JSON.stringify(enabled));
}

/** 注册 expo-notifications 展示策略（读取内存缓存，切换开关后立即生效） */
export function registerNotificationPresentationHandler(): void {
  Notifications.setNotificationHandler({
    handleNotification: async () => {
      const p = getNotificationPreferencesSync();
      return {
        shouldShowAlert: p.pushEnabled,
        shouldPlaySound: p.soundEnabled,
        shouldSetBadge: true,
        shouldShowBanner: p.pushEnabled,
        shouldShowList: p.pushEnabled,
      };
    },
  });
}
