/**
 * Snippet persistence adapter (docs/architecture/02).
 *
 * The typed seam between the snippet store and IndexedDB. Exposes plain async
 * functions returning domain `Snippet` objects; migrates every record on read.
 * Quota failures fail loud as a `StorageQuotaError` — normalized once in `db.put`
 * (see db.ts) — so the UI can warn rather than silently lose work.
 */

import { CURRENT_SNIPPET_VERSION, type Snippet } from '@core/snippet';
import { del, getAll, put, SNIPPETS_STORE } from './db';
import { migrateSnippet } from './snippet-migrations';

/** Load every snippet, upgrading each record to the current shape. */
export async function loadSnippets(): Promise<Snippet[]> {
  const records = await getAll<unknown>(SNIPPETS_STORE);
  return records.map(migrateSnippet);
}

/** Persist a snippet at the current schema version. Propagates quota failures. */
export async function saveSnippet(snippet: Snippet): Promise<void> {
  await put(SNIPPETS_STORE, { ...snippet, version: CURRENT_SNIPPET_VERSION });
}

/** Permanently remove a snippet by id. */
export async function deleteSnippet(id: string): Promise<void> {
  await del(SNIPPETS_STORE, id);
}
