/**
 * Read-time migration for CustomTheme records (docs/architecture/02 §4).
 *
 * Mirrors snippet/dataset migrations: every theme read from storage passes
 * through `migrateCustomTheme`, which fills missing/invalid fields and stamps
 * the current version. Unknown fields are tolerated (spread the original, only
 * fill gaps) so a record written by a newer build round-trips without loss.
 */

import { CURRENT_THEME_VERSION, type CustomTheme } from '@core/custom-theme';
import { isJsonObject } from '@core/spec-config';

/** Upgrade a raw stored record to the current CustomTheme shape. */
export function migrateCustomTheme(raw: unknown): CustomTheme {
  const r = { ...(raw as Record<string, unknown>) };
  return {
    ...r,
    id: typeof r.id === 'number' ? r.id : Number(r.id),
    version: CURRENT_THEME_VERSION,
    name: typeof r.name === 'string' ? r.name : 'Untitled theme',
    config: isJsonObject(r.config) ? r.config : {},
    created: typeof r.created === 'string' ? r.created : new Date(0).toISOString(),
    modified: typeof r.modified === 'string' ? r.modified : new Date(0).toISOString(),
  };
}
