/**
 * Dataset persistence wiring (docs/architecture/01 §5, spec §09E).
 *
 * A startup subscriber that write-throughs the `datasets` array to the IndexedDB
 * adapter via the shared `wireEntityWriteThrough` diff loop. The store stays
 * browser-free; failures surface as a toast rather than silent loss (spec §10).
 * There is no debounced auto-save here — datasets change on explicit create/edit/
 * delete, not per keystroke, so every change is a structural array edit.
 */

import { deleteDataset, saveDataset } from '../infrastructure/dataset-store';
import { entityStorageErrorNotification } from '../services/storage-errors';
import { notify } from '../stores/NotificationStore';
import { useDatasetStore } from '../stores/DatasetStore';
import { wireEntityWriteThrough } from './entity-persistence';

type Unsubscribe = () => void;

/** Persist dataset upserts and deletions whenever the array changes. */
export function wireDatasetPersistence(): Unsubscribe {
  return wireEntityWriteThrough(useDatasetStore, (s) => s.datasets, {
    save: saveDataset,
    remove: deleteDataset,
    onError: (op, err) => notify(entityStorageErrorNotification('dataset', op, err)),
  });
}
