package kr.lunaticbum.back.lun.configs.web

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import kr.lunaticbum.back.lun.configs.core.GlobalEnvironment
import kr.lunaticbum.back.lun.configs.core.GlobalEnvironment.Companion.ApiKeyWordKey
import kr.lunaticbum.back.lun.configs.core.GlobalEnvironment.Companion.EncType11
import kr.lunaticbum.back.lun.configs.core.GlobalEnvironment.Companion.EncTypeKey
import kr.lunaticbum.back.lun.utils.JwtUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.lang.Nullable
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.ModelAndView

@Component
class BumsInterceptor(

) : HandlerInterceptor {

    @Autowired
    lateinit var globalEvv : GlobalEnvironment
    @Autowired
    lateinit var jwtUtil: JwtUtil
    val WRITE_PERMISSION_KEY = "PERMISSION"

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        var skippResourcesExtension = arrayListOf(".js",".css").filter { request.requestURI.contains(it) }.size > 0
//        if (!skippResourcesExtension) {
//            println("===============================================")
//            println("==================== BEGIN ====================")
            println("Request URL ===> " + request.requestURL)
//        }


        return super.preHandle(request, response, handler)
    }

//    @Autowired
//    lateinit var rememberMeServices: RememberMeServices

    @Throws(Exception::class)
    override fun postHandle(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        @Nullable modelAndView: ModelAndView?
    ) {
        println("modelAndView modelMap size >>> ${modelAndView?.modelMap?.keys?.size}")
        // [수정] modelAndView가 null이 아닐 경우에만 로직을 실행하도록 변경합니다.
        if (modelAndView != null && modelAndView.hasView()) {
            modelAndView.modelMap.put(EncTypeKey, EncType11)
            modelAndView.modelMap.put(ApiKeyWordKey, "Def")

            val authentication = SecurityContextHolder.getContext().authentication
            val principal = authentication?.principal

            var jwtToken: String? = null
            if (principal is UserDetails) {
                jwtToken = jwtUtil.generateToken(principal)
            }
            modelAndView.modelMap.put("jwtToken", jwtToken)
        }else {

            println("modelAndView가 null이라 모델에 값 추가 불가")
        }


        super.postHandle(request, response, handler, modelAndView)
    }

}