package com.doctate.watch.audio

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 PendingCleanupTest {
    @get:Rule val tempDir = TemporaryFolder()

    private fun pendingDir(): File = tempDir.newFolder("unsynced")

    private fun touch(parent: File, name: String, mtime: Long): File {
        val f = File(parent, name)
        f.writeText("x")
        f.setLastModified(mtime)
        return f
    }

    @Test fun deletes_orphan_m4a_older_than_cutoff() {
        val dir = pendingDir()
        val now = 10_000_000L
        touch(dir, "case-a.m4a", mtime = now - 30_000L)
        val deleted = PendingCleanup.cleanupOrphanAudio(dir, ageCutoffMs = now - 10_000L)
        assertThat(deleted).isEqualTo(1)
        assertThat(File(dir, "case-a.m4a").exists()).isFalse()
    }

    @Test fun preserves_orphan_m4a_younger_than_cutoff() {
        val dir = pendingDir()
        val now = 10_000_000L
        touch(dir, "case-a.m4a", mtime = now - 5_000L)
        val deleted = PendingCleanup.cleanupOrphanAudio(dir, ageCutoffMs = now - 10_000L)
        assertThat(deleted).isEqualTo(0)
        assertThat(File(dir, "case-a.m4a").exists()).isTrue()
    }

    @Test fun preserves_paired_files_regardless_of_age() {
        val dir = pendingDir()
        val now = 10_000_000L
        touch(dir, "case-a.m4a", mtime = now - 30_000L)
        touch(dir, "case-a.meta.json", mtime = now - 30_000L)
        val deleted = PendingCleanup.cleanupOrphanAudio(dir, ageCutoffMs = now - 10_000L)
        assertThat(deleted).isEqualTo(0)
        assertThat(File(dir, "case-a.m4a").exists()).isTrue()
        assertThat(File(dir, "case-a.meta.json").exists()).isTrue()
    }

    @Test fun deletes_orphan_sidecar_older_than_cutoff() {
        val dir = pendingDir()
        val now = 10_000_000L
        touch(dir, "case-x.meta.json", mtime = now - 30_000L)
        val deleted = PendingCleanup.cleanupOrphanAudio(dir, ageCutoffMs = now - 10_000L)
        assertThat(deleted).isEqualTo(1)
        assertThat(File(dir, "case-x.meta.json").exists()).isFalse()
    }

    @Test fun deletes_tmp_leftovers_unconditionally() {
        val dir = pendingDir()
        val now = 10_000_000L
        // Tmp files might be brand new (interrupted write) — still delete.
        touch(dir, "case-a.m4a.tmp", mtime = now)
        touch(dir, "case-b.meta.json.tmp", mtime = now)
        val deleted = PendingCleanup.cleanupOrphanAudio(dir, ageCutoffMs = now - 10_000L)
        assertThat(deleted).isEqualTo(2)
    }

    @Test fun returns_zero_for_missing_dir() {
        val deleted = PendingCleanup.cleanupOrphanAudio(File(tempDir.root, "missing"), ageCutoffMs = 0L)
        assertThat(deleted).isEqualTo(0)
    }
}
