export const NOTIFICATION_PREFERENCES_KEY = "codexRemote.notificationPreferences";

export const NOTIFICATION_SETTING_GROUPS = [
  { id: "work", types: ["approval", "completed", "failed", "interrupted"] },
  { id: "usage", types: ["usage-exhausted", "usage-critical", "usage-low", "weekly-reset"] }
];

const KNOWN_TYPES = NOTIFICATION_SETTING_GROUPS.flatMap((group) => group.types);

export const DEFAULT_NOTIFICATION_PREFERENCES = Object.freeze({
  enabled: true,
  types: Object.freeze({
    approval: true,
    completed: true,
    failed: true,
    interrupted: true,
    "usage-exhausted": true,
    "usage-critical": false,
    "usage-low": false,
    "weekly-reset": false
  })
});

export function readNotificationPreferences(storage = safeStorage()) {
  try {
    const raw = storage?.getItem(NOTIFICATION_PREFERENCES_KEY);
    return raw ? sanitizePreferences(JSON.parse(raw)) : cloneDefaults();
  } catch {
    return cloneDefaults();
  }
}

export function writeNotificationPreferences(storage = safeStorage(), preferences) {
  if (!storage) return false;
  try {
    storage.setItem(NOTIFICATION_PREFERENCES_KEY, JSON.stringify(sanitizePreferences(preferences)));
    return true;
  } catch {
    return false;
  }
}

export function notificationPreferenceEnabled(preferences, type) {
  return Boolean(preferences?.enabled && KNOWN_TYPES.includes(type) && preferences.types?.[type]);
}

function sanitizePreferences(value = {}) {
  const defaults = cloneDefaults();
  return {
    enabled: typeof value.enabled === "boolean" ? value.enabled : defaults.enabled,
    types: Object.fromEntries(KNOWN_TYPES.map((type) => [
      type,
      typeof value.types?.[type] === "boolean" ? value.types[type] : defaults.types[type]
    ]))
  };
}

function cloneDefaults() {
  return { enabled: DEFAULT_NOTIFICATION_PREFERENCES.enabled, types: { ...DEFAULT_NOTIFICATION_PREFERENCES.types } };
}

function safeStorage() {
  return typeof window === "undefined" ? null : window.localStorage;
}
