import { SEARCH_HISTORY_KEY, SEARCH_HISTORY_MAX } from '@/constants/search'

function readRaw() {
  try {
    const raw = uni.getStorageSync(SEARCH_HISTORY_KEY)
    if (!raw) return []
    const list = typeof raw === 'string' ? JSON.parse(raw) : raw
    return Array.isArray(list) ? list : []
  } catch (e) {
    return []
  }
}

function writeRaw(list) {
  try {
    uni.setStorageSync(SEARCH_HISTORY_KEY, JSON.stringify(list))
  } catch (e) {
    // 存储失败不影响搜索
  }
}

/** 历史列表：{ keyword, time }[]，按 time 倒序 */
export function getSearchHistory() {
  return readRaw()
    .filter((item) => item && item.keyword)
    .sort((a, b) => (b.time || 0) - (a.time || 0))
}

/** 成功进入结果页后写入；同词去重并置顶 */
export function addSearchHistory(keyword) {
  const text = (keyword || '').trim()
  if (!text) return
  const now = Date.now()
  let list = readRaw().filter((item) => item.keyword !== text)
  list.unshift({ keyword: text, time: now })
  if (list.length > SEARCH_HISTORY_MAX) {
    list = list.slice(0, SEARCH_HISTORY_MAX)
  }
  writeRaw(list)
}

export function removeSearchHistoryItem(keyword) {
  const text = (keyword || '').trim()
  if (!text) return
  const list = readRaw().filter((item) => item.keyword !== text)
  writeRaw(list)
}

export function clearSearchHistory() {
  try {
    uni.removeStorageSync(SEARCH_HISTORY_KEY)
  } catch (e) {
    writeRaw([])
  }
}
