package com.github.nullptroma.wallenc.domain.vault.storages.common

import com.github.nullptroma.wallenc.domain.datatypes.StorageSyncJournalEntry
import com.github.nullptroma.wallenc.domain.datatypes.StorageSyncOperation
import com.github.nullptroma.wallenc.domain.datatypes.StorageSyncRevision
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.Instant
import java.util.concurrent.atomic.AtomicReference

class StorageSyncJournalBufferTest {

    @Test
    fun flushRestoresPendingOnWriteFailure() = runBlocking {
        val disk = AtomicReference(emptyMap<String, StorageSyncJournalEntry>())
        var shouldFail = true
        val buffer = StorageSyncJournalBuffer(
            syncActorId = "actor",
            originStorageUuid = null,
            readJournal = { disk.get() },
            writeJournal = {
                if (shouldFail) {
                    error("disk unavailable")
                }
                disk.set(it)
            },
        )
        val entry = buffer.buildEntry("/a.txt", StorageSyncOperation.UPSERT, 1L)
        try {
            buffer.appendEntry("/a.txt", entry)
        } catch (_: IllegalStateException) {
            // expected
        }
        shouldFail = false
        buffer.flushPending()
        assertTrue(disk.get().containsKey("/a.txt"))
        assertEquals(1L, disk.get()["/a.txt"]?.revision?.sequence)
    }
}
