package kr.or.bok.rtgs.louisvuitton

import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * 서비스 프로세스 제어 API(관리자 화면). admin 하위 경로라 기존 ADMIN JWT 인터셉터로 자동 보호.
 * 제어(start·stop·restart)는 rtgs.control.enabled 및 화이트리스트(controllable)로 이중 게이트.
 */
@RestController
class ServiceControlController(
    private val control: ServiceControlService,
) {
    /** 서비스 7 + 인프라 통합 상태(조회는 항상 허용). */
    @GetMapping("/admin/services")
    fun services(): Map<String, Any?> = control.status()

    @PostMapping("/admin/services/{id}/start")
    fun start(@PathVariable id: String) = guarded { control.start(id) }

    @PostMapping("/admin/services/{id}/stop")
    fun stop(@PathVariable id: String) = guarded { control.stop(id) }

    @PostMapping("/admin/services/{id}/restart")
    fun restart(@PathVariable id: String) = guarded { control.restart(id) }

    @GetMapping("/admin/services/{id}/log")
    fun log(@PathVariable id: String, @RequestParam(defaultValue = "120") lines: Int): Map<String, Any?> =
        control.tailLog(id, lines)

    private fun guarded(action: () -> Map<String, Any?>): ResponseEntity<Map<String, Any?>> {
        if (!control.enabled) return ResponseEntity.status(HttpStatus.CONFLICT)
            .body(mapOf("ok" to false, "message" to "서비스 제어 비활성화됨(rtgs.control.enabled=false)"))
        return try {
            ResponseEntity.ok(action())
        } catch (e: IllegalArgumentException) {
            ResponseEntity.badRequest().body(mapOf("ok" to false, "message" to (e.message ?: "잘못된 요청")))
        } catch (e: IllegalStateException) {
            ResponseEntity.status(HttpStatus.CONFLICT).body(mapOf("ok" to false, "message" to (e.message ?: "충돌")))
        } catch (e: Exception) {
            ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(mapOf("ok" to false, "message" to (e.message ?: "오류")))
        }
    }
}
