package com.correx.apps.server.workspace

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.writeText
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class WorkspaceFilesTest {

    @Test
    fun `lists all file types by relative path, sorted`(@TempDir root: Path) {
        root.resolve("src").createDirectories()
        root.resolve("src/Main.kt").writeText("fun main() {}")
        root.resolve("config.toml").writeText("a = 1") // not a source ext — must still appear
        root.resolve("README.md").writeText("# hi")

        val paths = WorkspaceFiles.list(root)

        assertEquals(listOf("README.md", "config.toml", "src/Main.kt"), paths)
    }

    @Test
    fun `skips ignored directories`(@TempDir root: Path) {
        root.resolve(".git").createDirectories()
        root.resolve(".git/HEAD").writeText("ref")
        root.resolve("node_modules/pkg").createDirectories()
        root.resolve("node_modules/pkg/index.js").writeText("x")
        root.resolve("keep.txt").writeText("y")

        val paths = WorkspaceFiles.list(root)

        assertEquals(listOf("keep.txt"), paths)
        assertFalse(paths.any { it.startsWith(".git") || it.startsWith("node_modules") })
    }

    @Test
    fun `caps the result count`(@TempDir root: Path) {
        repeat(10) { root.resolve("f$it.txt").writeText("x") }
        val paths = WorkspaceFiles.list(root, limit = 3)
        assertEquals(3, paths.size)
        assertTrue(paths.all { it.endsWith(".txt") })
    }

    @Test
    fun `missing root yields empty`(@TempDir root: Path) {
        val missing = root.resolve("nope")
        assertTrue(Files.notExists(missing))
        assertEquals(emptyList(), WorkspaceFiles.list(missing))
    }
}
