import {
  atomWithLocalStorage,
  getLocalStorageItem,
  setLocalStorageItem,
} from './utils/atomWithLocalStorage';

const SEARCH_CACHE_ENABLED = 'searchCacheEnabled';

/**
 * P4-8 — persistent encrypted-search cache opt-in flag (default `false`).
 *
 * Standalone, `localStorage`-backed boolean atom kept separate from
 * `state/settings.ts` on purpose. When `true`, encrypted-room search persists a
 * decrypted plaintext index to IndexedDB (`lotus-search-cache`) so coverage
 * survives reloads. Because this writes decrypted plaintext at rest it must be
 * explicitly opted into; the cache is clearable from the search UI and wiped on
 * logout. Toggling this atom off stops all reads/writes but does NOT wipe
 * existing data — that is the explicit "Clear cached index" button / logout.
 */
export const searchCacheEnabledAtom = atomWithLocalStorage<boolean>(
  SEARCH_CACHE_ENABLED,
  (key) => getLocalStorageItem<boolean>(key, false),
  (key, value) => setLocalStorageItem(key, value),
);
