/**
 * Snippet persistence & auto-save wiring (docs/architecture/01 §5).
 *
 * Bridges the pure SnippetStore to the IndexedDB adapter via startup
 * subscribers — the store stays browser-free, and all reads/writes funnel
 * through `infrastructure/`. Two subscribers:
 *
 *   1. Debounced auto-save: editor keystrokes (`draftText`) settle into a
 *      `commitDraft()` after a pause (spec §03B). Snippet-specific — the other
 *      entity tiers change on explicit actions, not per keystroke.
 *   2. Write-through: the shared `wireEntityWriteThrough` diff loop persists any
 *      change to the `snippets` array. Snippets use the richer
 *      `storageErrorNotification` (quota + load aware) rather than the generic
 *      entity toast.
 */

import { deleteSnippet, saveSnippet } from '../infrastructure/snippet-store';
import { storageErrorNotification } from '../services/storage-errors';
import { notify } from '../stores/NotificationStore';
import { useSnippetStore } from '../stores/SnippetStore';
import { wireEntityWriteThrough } from './entity-persistence';

/** Delay before a settled edit is committed to the stored draft (spec §03B). */
export const AUTOSAVE_DEBOUNCE_MS = 400;

type Unsubscribe = () => void;

/** Debounce `commitDraft` on editor-buffer changes. */
function wireDraftAutoSave(): Unsubscribe {
  let timer: ReturnType<typeof setTimeout> | undefined;
  return useSnippetStore.subscribe((s, prev) => {
    if (s.draftText === prev.draftText) return;
    clearTimeout(timer);
    timer = setTimeout(() => useSnippetStore.getState().commitDraft(), AUTOSAVE_DEBOUNCE_MS);
  });
}

/** Persist snippet upserts and deletions whenever the array changes. */
function wireWriteThrough(): Unsubscribe {
  return wireEntityWriteThrough(useSnippetStore, (s) => s.snippets, {
    save: saveSnippet,
    remove: deleteSnippet,
    onError: (op, err) => notify(storageErrorNotification(op, err)),
  });
}

/** Wire all persistence subscribers. Returns a teardown that detaches them. */
export function wireSnippetPersistence(): Unsubscribe {
  const unsubs = [wireDraftAutoSave(), wireWriteThrough()];
  return () => unsubs.forEach((u) => u());
}
