package com.correx.apps.server.tasks

import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.writeText

class FileTaskDocumentResolverTest {

    @TempDir
    lateinit var repo: Path

    private fun writeAdr() {
        val dir = repo.resolve("docs/decisions").also { it.createDirectories() }
        dir.resolve("adr-0007-redis.md").writeText(
            """
            ---
            name: "ADR 7 Redis Sessions"
            description: "use redis for session storage"
            ---

            # ADR 7: use redis for session storage

            **status:** accepted

            ## decision
            Redis backs session storage.
            """.trimIndent(),
        )
    }

    @Test
    fun `resolves an ADR id padding-agnostically`() = runBlocking {
        writeAdr()
        val resolver = FileTaskDocumentResolver(repo)

        val byShort = resolver.resolve("adr-7")
        val byPadded = resolver.resolve("ADR-0007")

        assertEquals("ADR 7 Redis Sessions", byShort?.title)
        assertEquals("use redis for session storage", byShort?.excerpt)
        assertEquals("docs/decisions/adr-0007-redis.md", byShort?.path)
        assertEquals(byShort, byPadded)
    }

    @Test
    fun `unknown ADR resolves to null`() = runBlocking {
        writeAdr()
        assertNull(FileTaskDocumentResolver(repo).resolve("adr-999"))
    }

    @Test
    fun `resolves an explicit markdown path and falls back to heading and first paragraph`() = runBlocking {
        repo.resolve("docs/notes").createDirectories()
        repo.resolve("docs/notes/plan.md").writeText("# Plan\n\nThe plan body.\n")

        val doc = FileTaskDocumentResolver(repo).resolve("docs/notes/plan.md")

        assertEquals("Plan", doc?.title)
        assertEquals("The plan body.", doc?.excerpt)
        assertEquals("docs/notes/plan.md", doc?.path)
    }

    @Test
    fun `non-document target resolves to null`() = runBlocking {
        assertNull(FileTaskDocumentResolver(repo).resolve("ext-123"))
    }
}
