import { get, set, del } from 'idb-keyval';
import type { YeetDoc } from './model';

const KEY = 'yeetpdf:autosave';

interface Saved {
  name: string;
  bytes: Uint8Array;
  annos: unknown;
  pages: unknown;
  meta: unknown;
  savedAt: number;
}

/** Persist the working document locally (never leaves the device). */
export async function autosave(doc: YeetDoc): Promise<void> {
  try {
    const payload: Saved = {
      name: doc.name,
      bytes: doc.bytes,
      annos: doc.annos,
      pages: doc.pages,
      meta: doc.meta,
      savedAt: Date.now(),
    };
    await set(KEY, payload);
  } catch {
    /* storage may be full or evicted; autosave is best-effort */
  }
}

export async function getRecovery(): Promise<Saved | null> {
  try {
    return (await get<Saved>(KEY)) ?? null;
  } catch {
    return null;
  }
}

export async function clearRecovery(): Promise<void> {
  try { await del(KEY); } catch { /* ignore */ }
}
