import { createMMKV } from 'react-native-mmkv';
import { createJSONStorage, type StateStorage } from 'zustand/middleware';

/**
 * The on-device key-value store. Glide is local-first: this MMKV instance is the
 * durable home of the task store (see task-store.ts) and the single source of
 * truth — not Convex. MMKV reads are synchronous, so the store hydrates before
 * the first render and there's no loading flash to design around.
 */
export const storage = createMMKV({ id: 'glide.local' });

/** Adapts MMKV to the `StateStorage` shape Zustand's `persist` middleware wants. */
const mmkvStateStorage: StateStorage = {
  getItem: (name) => storage.getString(name) ?? null,
  setItem: (name, value) => storage.set(name, value),
  removeItem: (name) => storage.remove(name),
};

/** JSON storage backed by MMKV, ready to hand to `persist({ storage })`. */
export const mmkvJSONStorage = createJSONStorage(() => mmkvStateStorage);
