package com.doctate.watch.domain

import com.doctate.watch.testfixtures.InMemoryCaseStore
import com.google.common.truth.Truth.assertThat
import java.io.File
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

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

    @Test fun sweeps_stale_synced_markers() = runTest {
        val store = InMemoryCaseStore()
        val now = 10_000_000_000L
        // Old + synced → eligible.
        val oldId = "case-old"
        store.markActivity(oldId, now = now - 100L * 3600L * 1000L) // 100h ago
        store.markSynced(oldId)
        // Recent + synced → keep.
        val recentId = "case-recent"
        store.markActivity(recentId, now = now - 1L * 3600L * 1000L) // 1h ago
        store.markSynced(recentId)

        StartupCleanup.run(
            store = store,
            pendingDir = tempDir.newFolder("pending"),
            nowMs = now,
            markerRetentionMs = 72L * 3600L * 1000L,
        )
        val ids = store.casesFlow.value.map { it.caseId }
        assertThat(ids).containsExactly(recentId)
    }

    @Test fun preserves_pending_markers_regardless_of_age() = runTest {
        val store = InMemoryCaseStore()
        val now = 10_000_000_000L
        val oldPendingId = "case-old-pending"
        store.markActivity(oldPendingId, now = now - 200L * 3600L * 1000L)
        // No markSynced — pending must be preserved.

        StartupCleanup.run(
            store = store,
            pendingDir = tempDir.newFolder("pending"),
            nowMs = now,
            markerRetentionMs = 72L * 3600L * 1000L,
        )
        val ids = store.casesFlow.value.map { it.caseId }
        assertThat(ids).containsExactly(oldPendingId)
    }

    @Test fun reaps_old_orphan_audio_in_pending_dir() = runTest {
        val store = InMemoryCaseStore()
        val pending = tempDir.newFolder("pending")
        val now = 10_000_000_000L
        // Old orphan m4a (no sidecar) — should die.
        File(pending, "old-orphan.m4a").apply {
            writeText("x"); setLastModified(now - 30L * 3600L * 1000L) // 30h ago
        }
        // Young orphan m4a — should survive (within 24h).
        File(pending, "fresh-orphan.m4a").apply {
            writeText("x"); setLastModified(now - 1L * 3600L * 1000L) // 1h ago
        }
        StartupCleanup.run(
            store = store,
            pendingDir = pending,
            nowMs = now,
            orphanAudioRetentionMs = 24L * 3600L * 1000L,
        )
        assertThat(File(pending, "old-orphan.m4a").exists()).isFalse()
        assertThat(File(pending, "fresh-orphan.m4a").exists()).isTrue()
    }
}
