const STORAGE_KEY = 'overdeck-inbox-snoozes'
import { loadRecord, saveRecord } from './browser-storage'

/** Default snooze window — tests may shorten via `window.__OVERDECK_SNOOZE_MS`. */
export const DEFAULT_SNOOZE_MS = 60 * 60 * 1000

export interface SnoozeMap {
  [itemId: string]: number
}

declare global {
  interface Window {
    __OVERDECK_SNOOZE_MS?: number
  }
}

export function snoozeDurationMs(): number {
  if (typeof window !== 'undefined' && typeof window.__OVERDECK_SNOOZE_MS === 'number') {
    return window.__OVERDECK_SNOOZE_MS
  }
  return DEFAULT_SNOOZE_MS
}

export function loadSnoozes(): SnoozeMap {
  return loadRecord(STORAGE_KEY, (value): value is number => typeof value === 'number')
}

export function saveSnoozes(snoozes: SnoozeMap): void {
  saveRecord(STORAGE_KEY, snoozes)
}

/** Item stays hidden until `item.ts` + the snooze duration elapses. */
export function snoozeUntilForItem(itemTs: string, durationMs = snoozeDurationMs()): number {
  return Date.parse(itemTs) + durationMs
}

export function isSnoozed(itemId: string, snoozes: SnoozeMap, now = Date.now()): boolean {
  const until = snoozes[itemId]
  if (until === undefined) return false
  return until > now
}

export function pruneExpiredSnoozes(snoozes: SnoozeMap, now = Date.now()): SnoozeMap {
  const next: SnoozeMap = {}
  for (const [id, until] of Object.entries(snoozes)) {
    if (until > now) next[id] = until
  }
  return next
}
