//package kr.lunaticbum.back.lun.service
//
//import io.jsonwebtoken.Claims
//import io.jsonwebtoken.Jws
//import io.jsonwebtoken.Jwts
//import jakarta.servlet.http.Cookie
//import jakarta.servlet.http.HttpServletRequest
//import jakarta.servlet.http.HttpServletResponse
//import kr.lunaticbum.back.lun.configs.GlobalEnvironment
//import kr.lunaticbum.back.lun.configs.JwtGenerator
//import kr.lunaticbum.back.lun.configs.JwtRule
//import kr.lunaticbum.back.lun.configs.TokenStatus
//import kr.lunaticbum.back.lun.model.*
//import kr.lunaticbum.back.lun.utils.BusinessException
//import kr.lunaticbum.back.lun.utils.ErrorCode
//import kr.lunaticbum.back.lun.utils.JwtUtil
//import lombok.extern.slf4j.Slf4j
//import org.springframework.beans.factory.annotation.Autowired
//import org.springframework.http.HttpHeaders
//import org.springframework.http.ResponseCookie
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
//import org.springframework.security.core.Authentication
//import org.springframework.security.core.token.Token
//import org.springframework.security.core.userdetails.UserDetails
//import org.springframework.stereotype.Service
//import org.springframework.transaction.annotation.Transactional
//import java.security.Key
//import java.time.Duration
//import java.util.*
//import java.util.function.Consumer
//
//
//@Service
//@Transactional(readOnly = true)
//@Slf4j
//class JwtService {
//
//    @Autowired
//    lateinit var globalEvv : GlobalEnvironment
//
//    @Autowired
//    private lateinit var jwtGenerator: JwtGenerator
//
//    @Autowired
//    private lateinit var jwtUtil: JwtUtil
//
//
//    @Autowired
//    private lateinit var customUserDetailsService: UserManager
//
//    @Autowired
//    private lateinit var tokenRepository : TokenDataRepository
//
////    private val ACCESS_SECRET_KEY: Key = jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY)
////    private val REFRESH_SECRET_KEY: Key = jwtUtil.getSigningKey(globalEvv.REFRESH_SECRET_KEY)
//
//    fun validateUser(requestUser: User) {
//        if (requestUser.getRole() === UserRole.NOT_REGISTERED) {
//            throw BusinessException(ErrorCode.NOT_AUTHENTICATED_USER)
//        }
//    }
//
//    @Transactional
//    fun generate(requestUser: User): TokenData? {
//        var accessToken =  jwtGenerator.generateAccessToken(jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY), globalEvv.ACCESS_EXPIRATION, requestUser)
//        var refreshToken =  jwtGenerator.generateRefreshToken(jwtUtil.getSigningKey(globalEvv.REFRESH_SECRET_KEY), globalEvv.REFRESH_EXPIRATION, requestUser)
//        var token = TokenData(accessToken, refreshToken)
//        return tokenRepository.save(token).block()
//    }
//
//
//    private fun setTokenToCookie(tokenPrefix: String, token: String, maxAgeSeconds: Long): ResponseCookie {
//        return ResponseCookie.from(tokenPrefix, token)
//            .path("/")
//            .maxAge(maxAgeSeconds)
//            .httpOnly(true)
//            .sameSite("None")
//            .secure(true)
//            .build()
//    }
//
//    fun validateAccessToken(token: String?): Boolean {
//        return jwtUtil.getTokenStatus(token, jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY)) == TokenStatus.AUTHENTICATED
//    }
//
//    fun validateRefreshToken(token: String?, refreshToken: String?): Boolean {
//        try {
//            val isRefreshValid = jwtUtil.getTokenStatus(refreshToken, jwtUtil.getSigningKey(globalEvv.REFRESH_SECRET_KEY)) == TokenStatus.AUTHENTICATED
//            val storedToken: TokenData? = tokenRepository.findBytokenKey(token ?: "").block(Duration.ofSeconds(10))
//            val isTokenMatched: Boolean = storedToken?.refreshToken.equals(refreshToken)
//            return isRefreshValid && isTokenMatched
//        } catch (e :Exception){
//
//        }
//        return false
//    }
//
//    fun resolveTokenFromCookie(request: HttpServletRequest, tokenPrefix: JwtRule?): String {
//        val cookies = request.cookies ?: throw BusinessException(ErrorCode.JWT_TOKEN_NOT_FOUND)
//        return jwtUtil.resolveTokenFromCookie(cookies, tokenPrefix!!)
//    }
//
//    fun getAuthentication(token: String): Authentication {
//        val principal: UserDetails = customUserDetailsService.loadUserByUsername(getUserPk(token, jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY)))
//        return UsernamePasswordAuthenticationToken(principal, "", principal.authorities)
//    }
//
//    private fun getUserPk(token: String, secretKey: Key): String {
//        return Jwts.parserBuilder()
//            .setSigningKey(secretKey)
//            .build()
//            .parseClaimsJws(token)
//            .getBody()
//            .getSubject()
//    }
//
//    fun getIdentifierFromRefresh(refreshToken: String?): String {
//        try {
//            return Jwts.parserBuilder()
//                .setSigningKey(jwtUtil.getSigningKey(globalEvv.REFRESH_SECRET_KEY))
//                .build()
//                .parseClaimsJws(refreshToken)
//                .getBody()
//                .getSubject()
//        } catch (e: Exception) {
//            throw BusinessException(ErrorCode.INVALID_JWT)
//        }
//    }
//
//    fun logout(token: String, response: HttpServletResponse) {
//        tokenRepository.deleteBytokenKey(token)
//
//        val accessCookie = jwtUtil.resetToken(JwtRule.ACCESS_PREFIX)
//        val refreshCookie = jwtUtil.resetToken(JwtRule.REFRESH_PREFIX)
//
//        response.addCookie(accessCookie)
//        response.addCookie(refreshCookie)
//    }
//    fun getUserIdFromToken(token: String?): String? {
//        try {
//            return jwtUtil.extractToken(token,jwtUtil.getSigningKey(globalEvv.ACCESS_SECRET_KEY))?.body?.get("Identifier")
//                .toString()
//        } catch (e: Exception) {
//            return null
//        }
//    }
//    fun getUserIdFromRefresh(token: String?): String? {
//        try {
//            return jwtUtil.extractToken(token,jwtUtil.getSigningKey(globalEvv.REFRESH_SECRET_KEY))?.body?.get("Identifier")
//                .toString()
//        } catch (e: Exception) {
//            return null
//        }
//    }
//
//
//
//    fun hasPerrmission(request: HttpServletRequest): Boolean {
//        var correctUserCheck = -1;
//        if (request.requestURI.contains("logout") == false && !request.cookies.isNullOrEmpty() && request.cookies.filter { it.name.equals("access") && it.value.length > 0 }.size > 0) {
//            var access : Cookie?= null
//            var refresh : Cookie?= null
//            request.cookies.forEach {
//                if (it.name.equals("access", true) && validateAccessToken(it.value)){
//                    access = it
//                    correctUserCheck += 1
//                }
//            }
//            request.cookies.forEach {
//                if (it.name.equals("refresh", true) && validateRefreshToken(access?.value,it.value)){
//                    refresh = it
//                    correctUserCheck += 1
//                }
//            }
//            if (correctUserCheck > 0) {
//                println("Response correctUserCheck ===> ${correctUserCheck}")
//            } else {
//                println("Response correctUserCheck ===> ${correctUserCheck}")
//            }
//        } else if (request.requestURI.contains("logout")) {
//
//        }
//        return correctUserCheck > 0
//    }
//}