import browser from 'webextension-polyfill'

export type DownloadHistoryItem = {
  gid: string
  downloader: 'aria' | 'native'
  startTime: string
  icon?: string | null
  name?: string | null
  path?: string | null
  status: 'queued' | 'downloading' | 'completed' | 'stop' | 'error'
  size: number
  downloaded: number
}

const HISTORY_KEY = 'history'

export async function getHistory(): Promise<DownloadHistoryItem[]> {
  const raw = (await browser.storage.local.get([HISTORY_KEY])) as Record<string, unknown>
  const history = raw[HISTORY_KEY]
  if (!Array.isArray(history)) return []
  return history as DownloadHistoryItem[]
}

export async function setHistory(next: DownloadHistoryItem[]): Promise<void> {
  await browser.storage.local.set({ [HISTORY_KEY]: next.slice(0, 300) })
}

export async function upsertHistory(item: DownloadHistoryItem): Promise<void> {
  const history = await getHistory()
  const idx = history.findIndex((v) => v.gid === item.gid)
  if (idx >= 0) {
    history[idx] = item
  } else {
    history.unshift(item)
  }
  await setHistory(history)
}
