package kr.lunaticbum.back.lun.controllers

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpSession
import kotlinx.coroutines.reactor.awaitSingle
import kr.lunaticbum.back.lun.model.KisAuthSession
import kr.lunaticbum.back.lun.model.KisConfigRequest
import kr.lunaticbum.back.lun.model.ResponceResult
import kr.lunaticbum.back.lun.model.ResultMV
import kr.lunaticbum.back.lun.model.UserManager
import kr.lunaticbum.back.lun.service.KisApiService
import kr.lunaticbum.back.lun.service.KisMarketService
import kr.lunaticbum.back.lun.utils.LogService
import org.springframework.http.ResponseEntity
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Controller
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
import org.springframework.web.reactive.function.client.WebClient

// src/main/kotlin/kr/lunaticbum/back/lun/controllers/StockController.kt (예시)

@Controller
@RequestMapping("/stock")
class StockViewController {
    @GetMapping("/config")
    fun configPage(): ResultMV = ResultMV("content/stock/config").apply { setTitle("Stock API 설정") }


    @GetMapping("/market")
    fun margketPage(): ResultMV = ResultMV("content/stock/market").apply { setTitle("Stock API 설정") }

}

@RestController
@RequestMapping("/api/stock")
class StockApiController(
    private val webClient: WebClient, // WebClientConfig.kt 활용
    private val userManager: UserManager,
    private val kisApiService: KisApiService,
    private val kisMarketService: KisMarketService,
    private val logService: LogService
) {
    @PostMapping("/config")
    suspend fun saveConfig(
        @RequestBody config: KisConfigRequest,
        session: HttpSession // 세션 주입
    ): ResponseEntity<ResponceResult> {
        return try {
            // 1. KIS 서버로 토큰 발급 테스트 (유효성 검사)
            val token = kisApiService.verifyAndGetToken(config).awaitSingle()

            // 2. DB 저장 없이 세션에만 저장 (브라우저 종료 시 삭제)
            val authInfo = KisAuthSession(
                appKey = config.appKey,
                appSecret = config.appSecret,
                accountNo = config.accountNo,
                accessToken = token
            )
            session.setAttribute("KIS_AUTH", authInfo)

            ResponseEntity.ok(ResponceResult().apply { resultCode = 0; resultMsg = "연결 성공" })
        } catch (e: Exception) {
            ResponseEntity.ok(ResponceResult().apply { resultCode = 7001; resultMsg = "연결 실패: ${e.message}" })
        }
    }

    @GetMapping("/market")
    suspend fun getMarketIndicators(): ResponseEntity<Map<String, Any>> {
        // 공용 혹은 세션에 저장된 키를 사용 (세션에 없다면 기본 시스템 키 사용 로직 필요)
        val token = "..." // 발급받은 토큰
        val appKey = "..."
        val appSecret = "..."

        val kospi = kisMarketService.getDomesticIndex("0001", token, appKey, appSecret).awaitSingle()
        val kosdaq = kisMarketService.getDomesticIndex("1001", token, appKey, appSecret).awaitSingle()

        // 응답 데이터 정리
        val result = mapOf(
            "kospi" to (kospi["output"] as Map<*, *>)["bstp_nmix_prpr"], // 현재가
            "kospi_change" to (kospi["output"] as Map<*, *>)["bstp_nmix_prdy_ctrt"], // 등락률
            "kosdaq" to (kosdaq["output"] as Map<*, *>)["bstp_nmix_prpr"],
            "kosdaq_change" to (kosdaq["output"] as Map<*, *>)["bstp_nmix_prdy_ctrt"]
        )

        return ResponseEntity.ok(result) as ResponseEntity<Map<String, Any>>
    }
}