import browser from 'webextension-polyfill'

export type ExtensionSettings = {
  extensionStatus: boolean
  useNativeHost: boolean
  activateAppOnDownload: boolean
  enableNotifications: boolean
  hideChromeBar: boolean
  showContextOption: boolean
  downloadFallback: boolean
  darkMode: boolean
  showOnlyAria: boolean
  minFileSize: number
  blacklist: string[]
  motrixPort: number
  motrixAPIkey: string
}

const DEFAULTS: ExtensionSettings = {
  extensionStatus: true,
  useNativeHost: true,
  activateAppOnDownload: true,
  enableNotifications: true,
  hideChromeBar: true,
  showContextOption: true,
  downloadFallback: false,
  darkMode: false,
  showOnlyAria: false,
  minFileSize: 0,
  blacklist: [],
  motrixPort: 16800,
  motrixAPIkey: '',
}

export async function getSettings(): Promise<ExtensionSettings> {
  const raw = (await browser.storage.sync.get(Object.keys(DEFAULTS))) as Record<string, unknown>
  return {
    extensionStatus: Boolean(raw.extensionStatus ?? DEFAULTS.extensionStatus),
    useNativeHost: Boolean(raw.useNativeHost ?? DEFAULTS.useNativeHost),
    activateAppOnDownload: Boolean(raw.activateAppOnDownload ?? DEFAULTS.activateAppOnDownload),
    enableNotifications: Boolean(raw.enableNotifications ?? DEFAULTS.enableNotifications),
    hideChromeBar: Boolean(raw.hideChromeBar ?? DEFAULTS.hideChromeBar),
    showContextOption: Boolean(raw.showContextOption ?? DEFAULTS.showContextOption),
    downloadFallback: Boolean(raw.downloadFallback ?? DEFAULTS.downloadFallback),
    darkMode: Boolean(raw.darkMode ?? DEFAULTS.darkMode),
    showOnlyAria: Boolean(raw.showOnlyAria ?? DEFAULTS.showOnlyAria),
    minFileSize: Number(raw.minFileSize ?? DEFAULTS.minFileSize),
    blacklist: Array.isArray(raw.blacklist) ? raw.blacklist.map((v) => String(v)) : DEFAULTS.blacklist,
    motrixPort: Number(raw.motrixPort ?? DEFAULTS.motrixPort),
    motrixAPIkey: String(raw.motrixAPIkey ?? DEFAULTS.motrixAPIkey),
  }
}

export async function saveSettings(next: Partial<ExtensionSettings>): Promise<void> {
  await browser.storage.sync.set(next)
}
