package com.correx.apps.server

import com.correx.core.approvals.Tier
import com.correx.core.events.events.ToolRequest
import com.correx.core.tools.contract.Tool
import com.correx.core.tools.contract.ToolCapability
import com.correx.core.tools.contract.ToolExecutor
import com.correx.core.tools.contract.ToolResult
import com.correx.core.tools.contract.ValidationResult
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.JsonObject
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
import java.nio.file.Path
import kotlin.test.assertEquals
import kotlin.test.assertNull

class McpIndexBootstrapTest {
    private val log = LoggerFactory.getLogger("test")

    private class FakeTool(override val name: String) : Tool, ToolExecutor {
        var seen: ToolRequest? = null
        override val description = ""
        override val parametersSchema = JsonObject(emptyMap())
        override val tier = Tier.T2
        override val requiredCapabilities = emptySet<ToolCapability>()
        override fun validateRequest(request: ToolRequest) = ValidationResult.Valid
        override suspend fun execute(request: ToolRequest): ToolResult {
            seen = request
            return ToolResult.Success(request.invocationId, "indexed")
        }
    }

    @Test
    fun `calls index_repository with repo_path set to the workspace root`() = runBlocking {
        val index = FakeTool("mcp__codebase-memory__index_repository")
        bootstrapCodebaseIndex(listOf(FakeTool("mcp__x__search_code"), index), Path.of("/repo"), log)
        assertEquals("/repo", index.seen?.parameters?.get("repo_path"))
    }

    @Test
    fun `no-op when no index_repository tool is mounted`() = runBlocking {
        val other = FakeTool("mcp__x__search_code")
        bootstrapCodebaseIndex(listOf(other), Path.of("/repo"), log)
        assertNull(other.seen)
    }
}
