package kr.or.bok.rtgs.louisvuitton

import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * 부하테스트 콘솔 API (인증 없는 `/console` 경로 — AdminAuthInterceptor는 `/admin` 경로만 보호).
 * 정적 화면(static/loadtest.html)이 이 엔드포인트를 호출한다. localhost 프로토타입 운영도구.
 */
@RestController
@RequestMapping("/console")
class LoadTestController(
    private val loadTest: LoadTestService,
    private val jdbc: JdbcTemplate,
) {
    @PostMapping("/loadtest/start")
    fun start(@RequestBody params: LoadTestParams): ResponseEntity<Map<String, Any?>> {
        return try {
            if (loadTest.start(params)) ResponseEntity.accepted().body(loadTest.status())
            else ResponseEntity.status(HttpStatus.CONFLICT)
                .body(mapOf("error" to "이미 실행 중인 부하테스트가 있습니다."))
        } catch (e: IllegalStateException) {
            ResponseEntity.badRequest().body(mapOf("error" to (e.message ?: "잘못된 요청")))
        }
    }

    @GetMapping("/loadtest/status")
    fun status(): Map<String, Any?> = loadTest.status()

    @PostMapping("/loadtest/stop")
    fun stop(): Map<String, Any?> {
        loadTest.stop()
        return mapOf("ok" to true, "running" to loadTest.isRunning)
    }

    @GetMapping("/loadtest/result")
    fun result(): Map<String, Any?> = loadTest.result()

    /** 원장 집계(읽기 전용) — 부하 전/후 스냅샷으로 총잔액 보존(0-합) 표시용. */
    @GetMapping("/ledger/summary")
    fun ledgerSummary(): Map<String, Any?> = mapOf(
        "byStatus" to jdbc.queryForList("SELECT status, count(*) AS cnt FROM transfer GROUP BY status ORDER BY status"),
        "totalBalance" to jdbc.queryForObject("SELECT COALESCE(sum(balance),0) FROM account", Long::class.java),
        "accounts" to jdbc.queryForObject("SELECT count(*) FROM account", Long::class.java),
        "transfers" to jdbc.queryForObject("SELECT count(*) FROM transfer", Long::class.java),
        "maxSeq" to jdbc.queryForObject("SELECT COALESCE(max(global_seq),0) FROM transfer", Long::class.java),
    )
}
