import AsyncStorage from "@react-native-async-storage/async-storage";

export const storageKeys = {
  settings: "@mapmapnav/settings",
  recents: "@mapmapnav/recents",
  territory: "@mapmapnav/territory",
  saved: "@mapmapnav/saved",
} as const;

/** Best-effort JSON read; any failure (missing key, corrupt data) returns `fallback`. */
export async function readJSON<T>(key: string, fallback: T): Promise<T> {
  try {
    const raw = await AsyncStorage.getItem(key);
    if (raw === null) return fallback;
    return JSON.parse(raw) as T;
  } catch {
    return fallback;
  }
}

/** Best-effort JSON write; the app stays usable in-memory if storage fails. */
export async function writeJSON<T>(key: string, value: T): Promise<void> {
  try {
    await AsyncStorage.setItem(key, JSON.stringify(value));
  } catch {
    // swallow — in-memory state remains correct for this session
  }
}
