package kr.lunaticbum.back.lun.utils

import jakarta.annotation.PostConstruct
import jakarta.annotation.PreDestroy
import jakarta.servlet.http.HttpServletRequest
import lombok.RequiredArgsConstructor
import org.springframework.context.annotation.Scope
import org.springframework.context.annotation.ScopedProxyMode
import org.springframework.stereotype.Component
import org.springframework.stereotype.Controller
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*


@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
class Logger {
    private var uuid: String? = null
    private var requestURL: String? = null
    fun setRequestURL(requestURL: String?) {
        this.requestURL = requestURL
    }

    fun log(message: String) {
        println("[$uuid] [$requestURL] $message")
    }



    @PostConstruct
    fun init() {
        uuid = UUID.randomUUID().toString()
        println("[$uuid] request scope bean create:$this")
    }

    @PreDestroy
    fun close() {
        println("[$uuid] request scope bean close:$this")
    }
}

@Service
@RequiredArgsConstructor
class LogService {


    fun logic(id: String) {
        println("service id = $id")
    }
    fun log(id: String) {
        println("log  = $id")
    }
}

@Controller
@RequiredArgsConstructor
class LogController {
    private val logService: LogService? = null
    private val myLogger: Logger? = null

    @RequestMapping("log-demo")
    @ResponseBody
    fun logDemo(request: HttpServletRequest): String {
        val requestURL = request.requestURL.toString()
        myLogger?.setRequestURL(requestURL)
        myLogger?.log("controller test")
        logService!!.logic("testId")
        return "OK"
    }
}