package kr.lunaticbum.back.lun.service

import kr.lunaticbum.back.lun.model.KisConfigRequest
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono

@Service
class KisApiService() {
    private val baseUrl = "https://openapi.koreainvestment.com:9443" // 실전투자용
    private val webClient: WebClient = WebClient.create(baseUrl)

    fun verifyAndGetToken(config: KisConfigRequest): Mono<String> {
        val body = mapOf(
            "grant_type" to "client_credentials",
            "appkey" to config.appKey,
            "appsecret" to config.appSecret
        )

        return webClient.post()
            .uri("$baseUrl/oauth2/tokenP")
            .bodyValue(body)
            .retrieve()
            .bodyToMono(Map::class.java)
            .map { it["access_token"]?.toString() ?: throw Exception("토큰 발급 실패") }
    }
}

@Service
class KisMarketService() {
    private val baseUrl = "https://openapi.koreainvestment.com:9443"
    private val webClient: WebClient = WebClient.create(baseUrl)
    // 1. 국내 지수 조회 (KOSPI: "0001", KOSDAQ: "1001")
    fun getDomesticIndex(indexCode: String, token: String, appKey: String, appSecret: String): Mono<Map<*, *>> {
        return WebClient.create(baseUrl).get()
            .uri { it.path("/uapi/domestic-stock/v1/quotations/inquire-index-price")
                .queryParam("FID_COND_MRKT_DIV_CODE", "U") // 업종
                .queryParam("FID_INPUT_ISCD", indexCode)
                .build()
            }
            .header("authorization", "Bearer $token")
            .header("appkey", appKey)
            .header("appsecret", appSecret)
            .header("tr_id", "FHPST01010000") // 업종 현재가 조회 TR
            .retrieve()
            .bodyToMono(Map::class.java)
    }

    // 2. 환율 및 해외 지수 조회 (환율: "FX@KRW", 나스닥: "NAS@IXIC")
    // ※ 해외 지수는 '해외주식 현재가 상세' API 등을 활용합니다.
    fun getMarketIndicator(symbol: String, token: String, appKey: String, appSecret: String): Mono<Map<*, *>> {
        return webClient.get()
            .uri { it.path("/uapi/overseas-stock/v1/quotations/price")
                .queryParam("AUTH", "")
                .queryParam("EXCD", symbol.split("@")[0]) // 거래소 코드
                .queryParam("SYMB", symbol.split("@")[1]) // 심볼
                .build()
            }
            .header("authorization", "Bearer $token")
            .header("appkey", appKey)
            .header("appsecret", appSecret)
            .header("tr_id", "HHDFS00000300") // 해외주식 현재가 상세 TR
            .retrieve()
            .bodyToMono(Map::class.java)
    }
}