import * as FileSystem from 'expo-file-system/legacy';

const BASE = FileSystem.documentDirectory ?? '';

// Async key-value storage backed by individual JSON files.
// Compatible with zustand/middleware createJSONStorage().
export const fileStorage = {
  getItem: async (name: string): Promise<string | null> => {
    try {
      const path = `${BASE}zs_${name}.json`;
      const info = await FileSystem.getInfoAsync(path);
      if (!info.exists) return null;
      return await FileSystem.readAsStringAsync(path);
    } catch {
      return null;
    }
  },

  setItem: async (name: string, value: string): Promise<void> => {
    try {
      const path = `${BASE}zs_${name}.json`;
      await FileSystem.writeAsStringAsync(path, value);
    } catch { /* silent — don't crash on storage failure */ }
  },

  removeItem: async (name: string): Promise<void> => {
    try {
      const path = `${BASE}zs_${name}.json`;
      await FileSystem.deleteAsync(path, { idempotent: true });
    } catch { /* silent */ }
  },
};
