/**
 * Custom theme persistence adapter (docs/architecture/02; scope doc §4.4).
 *
 * The typed seam between the CustomThemeStore and IndexedDB's `themes` object
 * store. Exposes plain async functions returning domain `CustomTheme` objects
 * and migrates every record on read — same contract as dataset-store.
 */

import { CURRENT_THEME_VERSION, type CustomTheme } from '@core/custom-theme';
import { THEMES_STORE, del, getAll, put } from './db';
import { migrateCustomTheme } from './theme-migrations';

/** Load every custom theme, upgrading each record to the current shape. */
export async function loadCustomThemes(): Promise<CustomTheme[]> {
  const records = await getAll<unknown>(THEMES_STORE);
  return records.map(migrateCustomTheme);
}

/** Persist a custom theme at the current schema version. Propagates failures. */
export async function saveCustomTheme(theme: CustomTheme): Promise<void> {
  await put(THEMES_STORE, { ...theme, version: CURRENT_THEME_VERSION });
}

/** Permanently remove a custom theme by id. */
export async function deleteCustomTheme(id: number): Promise<void> {
  await del(THEMES_STORE, id);
}
