import { createJsonStore } from './jsonStore'
import { QUEUE_MAX } from './constants'
import type { PersistedQueueItem, PersistedQueueStatus } from '@shared/ipc'

/**
 * Persistence for the download queue (M4). The queue lived only in renderer memory,
 * so `saved` / scheduled and other pending downloads were silently lost on quit.
 * The renderer now mirrors its durable items here (via `queueSave`) and rehydrates
 * them on launch (via `queueList`), so a parked/scheduled download returns.
 *
 * Reuses the shared cached-atomic `createJsonStore` (R1/R2/R3), so writes are atomic
 * and coalesced — the renderer can call `queueSave` freely on queue changes.
 */

const PERSISTED_STATUSES: readonly PersistedQueueStatus[] = [
  'queued',
  'downloading',
  'paused',
  'saved',
  'error'
]

/** Defensive row validator (a hand-edited or partially-written file can't crash a read). */
function isValidQueueItem(o: unknown): o is PersistedQueueItem {
  if (typeof o !== 'object' || o === null) return false
  const it = o as Record<string, unknown>
  return (
    typeof it.id === 'string' &&
    typeof it.url === 'string' &&
    typeof it.title === 'string' &&
    (it.kind === 'video' || it.kind === 'audio') &&
    typeof it.quality === 'string' &&
    typeof it.status === 'string' &&
    (PERSISTED_STATUSES as readonly string[]).includes(it.status)
  )
}

const store = createJsonStore('queue.json', isValidQueueItem, QUEUE_MAX)

export function listQueue(): PersistedQueueItem[] {
  return store.read()
}

export function saveQueue(items: PersistedQueueItem[]): void {
  store.write(items)
}
