//#region src/components/pisellLookup/utils/storage.ts
/**
* localStorage 工具函数
* 用于管理搜索历史的存储
*/
/**
* 从 localStorage 加载历史记录
* @param key 存储的 key
* @returns 历史记录数组
*/
const loadHistory = (key) => {
	try {
		const data = localStorage.getItem(key);
		if (!data) return [];
		return JSON.parse(data);
	} catch (error) {
		console.error("Failed to load history from localStorage:", error);
		return [];
	}
};
/**
* 保存历史记录到 localStorage
* @param key 存储的 key
* @param history 历史记录数组
* @param maxCount 最大数量限制
*/
const saveHistory = (key, history, maxCount) => {
	try {
		const limitedHistory = history.slice(0, maxCount);
		localStorage.setItem(key, JSON.stringify(limitedHistory));
	} catch (error) {
		console.error("Failed to save history to localStorage:", error);
	}
};
/**
* 清除历史记录
* @param key 存储的 key
*/
const clearHistory = (key) => {
	try {
		localStorage.removeItem(key);
	} catch (error) {
		console.error("Failed to clear history from localStorage:", error);
	}
};
/**
* 添加历史记录项
* @param key 存储的 key
* @param item 新的历史记录项
* @param maxCount 最大数量限制
* @returns 更新后的历史记录数组
*/
const addHistoryItem = (key, item, maxCount) => {
	try {
		const newHistory = [item, ...loadHistory(key).filter((h) => h !== item)];
		saveHistory(key, newHistory, maxCount);
		return newHistory.slice(0, maxCount);
	} catch (error) {
		console.error("Failed to add history item:", error);
		return [];
	}
};
/**
* 删除历史记录项
* @param key 存储的 key
* @param item 要删除的历史记录项
* @returns 更新后的历史记录数组
*/
const removeHistoryItem = (key, item) => {
	try {
		const newHistory = loadHistory(key).filter((h) => h !== item);
		localStorage.setItem(key, JSON.stringify(newHistory));
		return newHistory;
	} catch (error) {
		console.error("Failed to remove history item:", error);
		return [];
	}
};
//#endregion
export { addHistoryItem, clearHistory, loadHistory, removeHistoryItem };
