/**
 * Dataset persistence adapter (docs/architecture/02, spec §09E).
 *
 * The typed seam between the dataset store and IndexedDB's high-capacity
 * `datasets` object store (separate from snippets so large payloads live in a
 * tier suited to them). Exposes plain async functions returning domain `Dataset`
 * objects and migrates every record on read.
 */

import { CURRENT_DATASET_VERSION, type Dataset } from '@core/dataset';
import { DATASETS_STORE, del, getAll, put } from './db';
import { migrateDataset } from './dataset-migrations';

/** Load every dataset, upgrading each record to the current shape. */
export async function loadDatasets(): Promise<Dataset[]> {
  const records = await getAll<unknown>(DATASETS_STORE);
  return records.map(migrateDataset);
}

/** Persist a dataset at the current schema version. Propagates failures. */
export async function saveDataset(dataset: Dataset): Promise<void> {
  await put(DATASETS_STORE, { ...dataset, version: CURRENT_DATASET_VERSION });
}

/** Permanently remove a dataset by id. */
export async function deleteDataset(id: number): Promise<void> {
  await del(DATASETS_STORE, id);
}
