import { get, set, del } from 'idb-keyval'

export type OfflineOperation = {
    id: string
    type: string
    payload: any
    timestamp: number
}

const STORE_KEY = 'offline-queue'

async function readAll(): Promise<OfflineOperation[]> {
    const data = await get<OfflineOperation[]>(STORE_KEY)
    return data || []
}

export async function enqueue(op: Omit<OfflineOperation, 'id' | 'timestamp'>) {
    const current = await readAll()
    current.push({ ...op, id: crypto.randomUUID(), timestamp: Date.now() })
    await set(STORE_KEY, current)
}

export async function flush(handler: (op: OfflineOperation) => Promise<void>) {
    const queue = await readAll()
    for (const op of queue) {
        try {
            await handler(op)
            await remove(op.id)
        } catch (err) {
            console.error('Failed to process offline op', op, err)
            // stop flush on first failure to avoid loop
            break
        }
    }
}

export async function remove(id: string) {
    const current = await readAll()
    const updated = current.filter((o) => o.id !== id)
    await set(STORE_KEY, updated)
}

export async function clear() {
    await del(STORE_KEY)
} 