import type { ErrorLogEntry } from '@shared/ipc'
import { isValidErrorLogEntry } from './core/validation'
import { createJsonStore } from './jsonStore'
import { ERRORLOG_MAX_ENTRIES } from './constants'

// Plain JSON in userData, same shape as history.ts. Persisted so a failure
// report survives the queue item being cleared (Seal's "debug report"). Atomic
// writes / corruption backup / caching come from the shared jsonStore (R1–R3).
// Per-entry validation (isValidErrorLogEntry) so a hand-edited or corrupted
// errorlog.json can't feed the UI entries with the wrong shape. (audit S5)
const store = createJsonStore('errorlog.json', isValidErrorLogEntry, ERRORLOG_MAX_ENTRIES)

export function listErrorLog(): ErrorLogEntry[] {
  return store.read()
}

export function addErrorLog(entry: ErrorLogEntry): ErrorLogEntry[] {
  return store.write([entry, ...listErrorLog()])
}

export function clearErrorLog(): ErrorLogEntry[] {
  return store.write([])
}
