// ─── Safe Persist Storage ─────────────────────────────────────────────────────
// Wraps localStorage with error handling for Zustand persist middleware.
// Handles: quota exceeded, corrupted JSON, and unexpected read/write failures.
//
// Zustand persist storage contract:
//   getItem(name)  → returns parsed object { state, version } | null
//   setItem(name, value) → receives object { state, version }, must serialize
//   removeItem(name) → removes the key

import type { StateStorage } from 'zustand/middleware';

/**
 * Creates a safe localStorage wrapper for Zustand persist.
 * - Corrupted JSON → returns null (Zustand uses initial state)
 * - Quota exceeded → logs warning, skips write
 * - Other errors → logs warning, graceful fallback
 */
export function createSafeStorage(): StateStorage {
  const storage: StateStorage = {
    getItem: (name: string): string | null | Promise<string | null> => {
      try {
        const str = localStorage.getItem(name);
        if (str === null) return null;
        // Zustand expects the parsed storage envelope { state, version }
        return JSON.parse(str);
      } catch (error) {
        // Corrupted JSON or other read error — clear the bad data
        try {
          localStorage.removeItem(name);
        } catch {
          // ignore
        }
        return null;
      }
    },
    setItem: (name: string, value: unknown): void => {
      try {
        // Zustand passes the storage envelope { state, version } as a JS object
        localStorage.setItem(name, JSON.stringify(value));
      } catch (error) {
        console.error('[safe-persist] Failed to persist:', name, error);
      }
    },
    removeItem: (name: string): void => {
      try {
        localStorage.removeItem(name);
      } catch (error) {
        // ignore
      }
    },
  };
  return storage;
}
