package com.doctate.watch.net

import com.doctate.watch.domain.OnelinerEntry
import com.doctate.watch.domain.OnelinerState
import com.doctate.watch.domain.OnelinersResponse
import com.google.common.truth.Truth.assertThat
import java.io.File
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

class SnapshotCacheTest {
    @get:Rule val tempDir = TemporaryFolder()

    private fun newCache(): SnapshotCache = SnapshotCache(File(tempDir.root, "cache.json"))

    @Test fun load_returns_null_when_file_missing() {
        assertThat(newCache().load()).isNull()
    }

    @Test fun store_then_load_roundtrips_full_snapshot() {
        val cache = newCache()
        val snap = CachedSnapshot(
            etag = "W/\"abc-72\"",
            fetchedAt = "2026-04-26T12:00:00Z",
            response = OnelinersResponse(
                asOf = "2026-04-26T12:00:00Z",
                windowHours = 72,
                oneliners = listOf(
                    OnelinerEntry(
                        caseId = "c-1",
                        oneliner = OnelinerState.Ready("hello", "2026-04-26T11:00:00Z"),
                        createdAt = "2026-04-26T10:00:00Z",
                        lastRecordingAt = "2026-04-26T10:30:00Z",
                        updatedAt = "2026-04-26T11:00:00Z",
                    ),
                ),
            ),
        )
        cache.store(snap)
        val loaded = cache.load()
        assertThat(loaded).isEqualTo(snap)
    }

    @Test fun load_returns_null_on_corrupted_file() {
        val cache = newCache()
        File(tempDir.root, "cache.json").writeText("not json", Charsets.UTF_8)
        assertThat(cache.load()).isNull()
    }

    @Test fun clear_removes_file() {
        val cache = newCache()
        cache.store(
            CachedSnapshot(
                etag = "x",
                fetchedAt = "2026-04-26T12:00:00Z",
                response = OnelinersResponse("2026-04-26T12:00:00Z", 72, emptyList()),
            ),
        )
        cache.clear()
        assertThat(File(tempDir.root, "cache.json").exists()).isFalse()
    }
}
