package kr.or.bok.rtgs.chanel

import kr.or.bok.rtgs.chanel.jpa.RawMessageRepository
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

/**
 * 메타/원문 조회 API.
 * - /meta/labels: transfer 컬럼의 한글명(DB 코멘트=데이터 사전)을 조회 필드명(camelCase)에 매핑해 반환.
 *   화면 라벨의 단일 출처가 DB 코멘트가 되도록 함.
 * - /rawmessage/{bmi}: 접수된 ISO20022 pacs.008 원문 전문(XML) 조회.
 */
@RestController
class MetaController(
    private val jdbc: JdbcTemplate,
    private val rawRepo: RawMessageRepository,
) {
    @GetMapping("/meta/labels")
    fun labels(): Map<String, String> {
        val rows = jdbc.queryForList(
            """
            SELECT a.attname AS col, col_description(a.attrelid, a.attnum) AS ko
            FROM pg_attribute a
            WHERE a.attrelid = 'transfer'::regclass AND a.attnum > 0 AND NOT a.attisdropped
            ORDER BY a.attnum
            """.trimIndent()
        )
        val m = LinkedHashMap<String, String>()
        for (r in rows) {
            val col = r["col"] as? String ?: continue
            val ko = r["ko"] as? String ?: continue
            m[toCamel(col)] = ko
        }
        return m
    }

    @GetMapping("/rawmessage/{bmi}")
    fun rawMessage(@PathVariable bmi: String): Map<String, Any?> {
        val e = rawRepo.findById(bmi).orElse(null)
            ?: return mapOf("bmi" to bmi, "found" to false)
        return mapOf(
            "bmi" to e.bmi,
            "msgType" to e.msgType,
            "receivedAt" to e.receivedAt,
            "originCenter" to e.originCenter,
            "rawXml" to e.rawXml,
            "found" to true,
        )
    }

    private fun toCamel(s: String): String =
        s.split("_").mapIndexed { i, p -> if (i == 0) p else p.replaceFirstChar { it.uppercase() } }.joinToString("")
}
