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

import { ensureStableIds, createEmptyItem } from './items';

/**
 * Migrate legacy 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 heading =
		typeof raw.heading === 'string'
			? raw.heading
			: typeof raw.title === 'string'
				? raw.title
				: '';
	const intro = typeof raw.intro === 'string' ? raw.intro : '';
	let items = Array.isArray(raw.items) ? raw.items : [];

	items = ensureStableIds(items);
	if (items.length === 0) {
		items = [createEmptyItem()];
	}

	const displayMode =
		raw.displayMode === 'static' || raw.displayMode === 'accordion'
			? raw.displayMode
			: 'accordion';

	return {
		schemaVersion: 1,
		heading,
		intro,
		items,
		displayMode,
		stylePreset:
			typeof raw.stylePreset === 'string' && raw.stylePreset
				? raw.stylePreset
				: 'accordion-cards',
		colorPreset:
			typeof raw.colorPreset === 'string' && raw.colorPreset
				? raw.colorPreset
				: 'blue',
		density:
			typeof raw.density === 'string' && raw.density
				? raw.density
				: 'comfortable',
		openFirstItem: !!raw.openFirstItem,
		showQuestionNumbers: !!raw.showQuestionNumbers,
		sharpCorners: !!raw.sharpCorners,
	};
}
