/**
 * Attribute migrations for the HowTo block (pure, no WordPress runtime).
 */

import { ensureStableIds, createEmptyStep } from './steps';
import { normalizeStringList } from './string-list';

/**
 * Migrate legacy / stub attribute bags to schemaVersion 1.
 *
 * @param {Object} attributes Raw attributes from an older save.
 * @return {Object} Migrated attributes.
 */
export function migrateToV1(attributes = {}) {
	const raw = attributes && typeof attributes === 'object' ? attributes : {};
	const name =
		typeof raw.name === 'string'
			? raw.name
			: typeof raw.title === 'string'
				? raw.title
				: '';
	const description =
		typeof raw.description === 'string'
			? raw.description
			: typeof raw.summary === 'string'
				? raw.summary
				: '';

	let steps = Array.isArray(raw.steps) ? raw.steps : [];
	steps = ensureStableIds(steps);
	if (steps.length === 0) {
		steps = [createEmptyStep()];
	}

	const displayModes = ['numbered', 'cards', 'compact'];
	const stylePresets = ['clean', 'bordered', 'soft-cards', 'editorial', 'minimal', 'dark'];
	const colorPresets = ['blue', 'green', 'purple', 'orange', 'dark', 'neutral'];
	const densities = ['compact', 'comfortable', 'spacious'];

	const cost =
		raw.estimatedCost && typeof raw.estimatedCost === 'object'
			? raw.estimatedCost
			: {};

	return {
		schemaVersion: 1,
		name,
		description,
		steps,
		supplies: normalizeStringList(raw.supplies),
		tools: normalizeStringList(raw.tools),
		totalTime: typeof raw.totalTime === 'string' ? raw.totalTime : '',
		estimatedCost: {
			currency: typeof cost.currency === 'string' ? cost.currency : '',
			value:
				cost.value === null || cost.value === undefined
					? ''
					: String(cost.value),
		},
		displayMode: displayModes.includes(raw.displayMode)
			? raw.displayMode
			: 'numbered',
		stylePreset: stylePresets.includes(raw.stylePreset)
			? raw.stylePreset
			: 'clean',
		colorPreset: colorPresets.includes(raw.colorPreset)
			? raw.colorPreset
			: 'blue',
		density: densities.includes(raw.density) ? raw.density : 'comfortable',
	};
}
