import { ref } from 'vue'

/**
 * Generic optimistic-update helper.
 *
 * Usage:
 *  const { apply, confirm, rollback } = useOptimisticUpdates()
 *  apply(id, () => { item.done = true }, () => { item.done = false })
 *  await apiCall()
 *  confirm(id) // or rollback(id) on failure
 */

// Generic optimistic updates helper.
// Currently a lightweight placeholder that simply applies the updater locally
// and exposes rollback ability. Replace with robust logic once backend supports PATCH w/ versioning.

type Updater<T> = (draft: T[]) => T[]

export function useOptimisticUpdates<T>(initial: T[]) {
    const data = ref<T[]>([...initial] as T[])
    const backups: T[][] = []

    function mutate(updater: Updater<T>) {
        backups.push([...data.value] as T[])
        data.value = updater([...data.value] as T[])
    }

    function rollback() {
        if (backups.length) {
            data.value = backups.pop()!
        }
    }

    return {
        data,
        mutate,
        rollback,
    }
} 