package de.arxsilex.maptools.converter.core.pbf

import java.nio.file.Files
import kotlin.io.path.createTempDirectory
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class PbfBlockIndexStoreTest {
    @Test
    fun `round trips versioned index and validates source identity`() {
        val directory = createTempDirectory("maptools-index-test")
        val source = directory.resolve("sample.osm.pbf")
        val indexFile = directory.resolve("sample.mtcidx")
        Files.write(source, byteArrayOf(1, 2, 3, 4))
        val index = PbfBlockIndex(
            sourceSize = Files.size(source),
            sourceLastModifiedMillis = Files.getLastModifiedTime(source).toMillis(),
            sourceSha256 = "9f64a747e1b97f131fabb6b447296c9b6f0201e79fb3c5356e6c77e89b6a806a",
            entries = listOf(
                PbfBlockIndexEntry(0, 0, "OSMHeader", 13, 21, 18, PbfCompression.ZLIB),
                PbfBlockIndexEntry(1, 38, "OSMData", 12, 45, 120, PbfCompression.ZLIB),
            ),
        )

        try {
            PbfBlockIndexStore.write(index, indexFile)
            val restored = PbfBlockIndexStore.read(indexFile)

            assertEquals(index, restored)
            assertTrue(PbfBlockIndexStore.matchesSource(restored, source))
            assertTrue(PbfBlockIndexStore.matchesSource(restored, source, verifySha256 = true))
            Files.write(source, byteArrayOf(4, 3, 2, 1))
            Files.setLastModifiedTime(
                source,
                java.nio.file.attribute.FileTime.fromMillis(index.sourceLastModifiedMillis),
            )
            assertTrue(PbfBlockIndexStore.matchesSource(restored, source))
            assertFalse(PbfBlockIndexStore.matchesSource(restored, source, verifySha256 = true))
        } finally {
            directory.toFile().deleteRecursively()
        }
    }
}
