/**
 * UndoManager — snapshot/restore pour les actions destructives.
 *
 * Stocke un seul niveau d'undo (le dernier snapshot).
 * Le snapshot expire après EXPIRY_MS.
 */

const EXPIRY_MS = 10_000;

interface Snapshot {
  stateJson: string;
  label: string;
  timestamp: number;
}

let current: Snapshot | null = null;
let onUndoCallback: (() => void) | null = null;

export const UndoManager = {
  /**
   * Sauvegarde un snapshot du state avant une action destructive.
   */
  snapshot(stateJson: string, label: string): void {
    current = { stateJson, label, timestamp: Date.now() };
  },

  /**
   * Restaure le dernier snapshot si disponible et non expiré.
   * Retourne true si l'undo a été effectué.
   */
  undo(): boolean {
    if (!this.canUndo()) return false;
    const api = (window as any).electronAPI;
    if (!api?.saveData) return false;

    api.saveData(current!.stateJson);
    current = null;

    if (onUndoCallback) onUndoCallback();
    else window.location.reload();

    return true;
  },

  canUndo(): boolean {
    if (!current) return false;
    if (Date.now() - current.timestamp > EXPIRY_MS) {
      current = null;
      return false;
    }
    return true;
  },

  label(): string {
    return current?.label ?? '';
  },

  clear(): void {
    current = null;
  },

  /** Callback custom après undo (par défaut: reload) */
  onUndo(cb: () => void): void {
    onUndoCallback = cb;
  },

  /**
   * Prend un snapshot du state actuel via electronAPI.
   * Retourne true si le snapshot a été pris.
   */
  async snapshotCurrent(label: string): Promise<boolean> {
    const api = (window as any).electronAPI;
    if (!api?.loadData) return false;
    const raw = await api.loadData();
    if (!raw) return false;
    this.snapshot(raw, label);
    return true;
  },
};
