const HISTORY_KEY = 'search:history'

export function readSearchHistory() {
	try {
		const list = uni.getStorageSync(HISTORY_KEY)
		return Array.isArray(list) ? list : []
	} catch (_) {
		return []
	}
}

export function pushSearchHistory(keywords) {
	const text = String(keywords || '').trim()
	if (!text) return readSearchHistory()
	let list = readSearchHistory()
	list = list.filter((item) => item && item.keywords !== text)
	list.unshift({ keywords: text })
	if (list.length > 20) list = list.slice(0, 20)
	try {
		uni.setStorageSync(HISTORY_KEY, list)
	} catch (_) {}
	return list
}

export function clearSearchHistory() {
	try {
		uni.removeStorageSync(HISTORY_KEY)
	} catch (_) {}
	return []
}
