package kr.or.bok.rtgs.chanel

import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * 서비스별 처리 현황(대사) 조회 — 읽기 전용. 각 서비스가 남긴 PostgreSQL 테이블을 최신순으로 반환.
 *  - transfer      : 원장(Dior 접수 PDNG → Hermes 결제 ACSP → Prada 완결 ACCC 흐름)
 *  - journal_log   : Hermes 선저널(write-ahead)
 *  - settlement_view: Prada 조회 사본
 *  - raw_message   : Chanel 원전문(pacs.008)
 */
@RestController
class LedgerController(private val jdbc: JdbcTemplate) {

    private fun q(sql: String, limit: Int) = jdbc.queryForList(sql.replace("{L}", limit.coerceIn(1, 200).toString()))

    @GetMapping("/ledger/transfers")
    fun transfers(@RequestParam(defaultValue = "20") limit: Int) = q(
        "SELECT bmi, global_seq, status, sender_code, receiver_code, amount, origin_center, updated_at " +
            "FROM transfer ORDER BY global_seq DESC NULLS LAST LIMIT {L}", limit)

    @GetMapping("/ledger/journal")
    fun journal(@RequestParam(defaultValue = "20") limit: Int) = q(
        "SELECT global_seq, bmi, applied, seq_epoch_millis FROM journal_log ORDER BY global_seq DESC LIMIT {L}", limit)

    @GetMapping("/ledger/views")
    fun views(@RequestParam(defaultValue = "20") limit: Int) = q(
        "SELECT bmi, global_seq, final_status, debtor_balance_after, creditor_balance_after, processed_center, finalized_at " +
            "FROM settlement_view ORDER BY global_seq DESC NULLS LAST LIMIT {L}", limit)

    @GetMapping("/ledger/rawmessages")
    fun rawmessages(@RequestParam(defaultValue = "20") limit: Int) = q(
        "SELECT bmi, msg_type, origin_center, received_at FROM raw_message ORDER BY received_at DESC LIMIT {L}", limit)

    /** 요약: 상태별 건수 + 총액(대사) */
    @GetMapping("/ledger/summary")
    fun summary(): Map<String, Any?> {
        val byStatus = jdbc.queryForList("SELECT status, count(*) AS cnt FROM transfer GROUP BY status ORDER BY status")
        val total = jdbc.queryForObject("SELECT sum(balance) FROM account", Long::class.java)
        val accts = jdbc.queryForObject("SELECT count(*) FROM account", Long::class.java)
        return mapOf("byStatus" to byStatus, "totalBalance" to total, "accounts" to accts)
    }
}
