import browser from 'webextension-polyfill'
import type { MediaCandidate } from './mediaCapture'

const KEY = 'media_candidates'
const MAX_ITEMS = 200

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

export async function setMediaCandidates(items: MediaCandidate[]): Promise<void> {
  const sorted = [...items].sort((a, b) => b.detectedAt - a.detectedAt)
  await browser.storage.local.set({ [KEY]: sorted.slice(0, MAX_ITEMS) })
}

export async function upsertMediaCandidate(candidate: MediaCandidate, fingerprint: string): Promise<void> {
  const items = await listMediaCandidates()
  const index = items.findIndex((v) => {
    try {
      const parsed = new URL(v.url)
      return `${parsed.protocol}//${parsed.host}${parsed.pathname}`.toLowerCase() === fingerprint
    } catch {
      return v.url.toLowerCase() === fingerprint
    }
  })

  if (index >= 0) {
    items[index] = {
      ...items[index],
      ...candidate,
      detectedAt: Date.now(),
    }
  } else {
    items.unshift(candidate)
  }

  await setMediaCandidates(items)
}

export async function clearMediaCandidates(): Promise<void> {
  await browser.storage.local.set({ [KEY]: [] })
}
