import { get, set } from 'idb-keyval';
import { uid } from './util';

const KEY = 'yeetpdf:signatures';
const LAST_KEY = 'yeetpdf:lastSignature';
const MAX = 12;

export interface SignatureData {
  dataUrl: string;
  w: number;
  h: number;
}

export interface SavedSignature {
  id: string;
  dataUrl: string;
  w: number;
  h: number;
  createdAt: number;
}

/** Saved signatures live only on this device (IndexedDB). */
export async function getSignatures(): Promise<SavedSignature[]> {
  try {
    return (await get<SavedSignature[]>(KEY)) ?? [];
  } catch {
    return [];
  }
}

export async function saveSignature(sig: { dataUrl: string; w: number; h: number }): Promise<SavedSignature> {
  const list = await getSignatures();
  const existing = list.find((s) => s.dataUrl === sig.dataUrl);
  if (existing) {
    // bump to front
    const reordered = [existing, ...list.filter((s) => s.id !== existing.id)];
    try { await set(KEY, reordered); } catch { /* ignore */ }
    return existing;
  }
  const item: SavedSignature = { id: uid('sig_'), dataUrl: sig.dataUrl, w: sig.w, h: sig.h, createdAt: Date.now() };
  const next = [item, ...list].slice(0, MAX);
  try { await set(KEY, next); } catch { /* storage may be full/evicted */ }
  return item;
}

export async function deleteSignature(id: string): Promise<void> {
  const list = await getSignatures();
  try { await set(KEY, list.filter((s) => s.id !== id)); } catch { /* ignore */ }
}

/** The most recently placed signature (for one-click reuse). */
export async function getLastSignature(): Promise<SignatureData | null> {
  try {
    return (await get<SignatureData>(LAST_KEY)) ?? null;
  } catch {
    return null;
  }
}
export async function setLastSignature(sig: SignatureData): Promise<void> {
  try { await set(LAST_KEY, { dataUrl: sig.dataUrl, w: sig.w, h: sig.h }); } catch { /* ignore */ }
}
