/**
 * Latest-wins reconciliation for optimistic store mutations (L142).
 *
 * The main-process mutation handlers (history/templates/sources) return the
 * authoritative persisted state — validated, capped, sanitized — but the stores
 * update optimistically first, so applying every response verbatim can briefly
 * roll back a newer optimistic update when calls overlap (add A, add B, response
 * A arrives without B). Each mutation therefore registers under a key; a
 * response is applied only if no newer call on that key has been issued since.
 * Responses for one key resolve in invoke order (main handles them
 * sequentially), so the applied response is always the newest state.
 */
export type Reconcile = <T>(
  key: string,
  call: Promise<T>,
  apply: (value: T) => void,
  onError: (e: unknown) => void
) => void

export function createReconciler(): Reconcile {
  const latest = new Map<string, number>()
  return (key, call, apply, onError) => {
    const seq = (latest.get(key) ?? 0) + 1
    latest.set(key, seq)
    call.then((value) => {
      if (latest.get(key) === seq) apply(value)
    }, onError)
  }
}
