package kr.lunaticbum.back.lun.configs

import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import kr.lunaticbum.back.lun.model.User
import lombok.Getter
import lombok.RequiredArgsConstructor
import org.springframework.stereotype.Component
import java.security.Key
import java.util.*
import kotlin.collections.HashMap


@Component
class JwtGenerator {
    fun generateAccessToken(ACCESS_SECRET: Key?, ACCESS_EXPIRATION: Long, user: User): String {
        val now = System.currentTimeMillis()

        return Jwts.builder()
            .setHeader(createHeader())
            .setClaims(createClaims(user))
            .setSubject(user.userId)
            .setExpiration(Date(now + ACCESS_EXPIRATION))
            .signWith(ACCESS_SECRET, SignatureAlgorithm.HS256)
            .compact()
    }

    fun generateRefreshToken(REFRESH_SECRET: Key?, REFRESH_EXPIRATION: Long, user: User): String {
        val now = System.currentTimeMillis()

        return Jwts.builder()
            .setHeader(createHeader())
            .setClaims(createClaims(user))
            .setSubject(user.getIdentifier())
            .setExpiration(Date(now + REFRESH_EXPIRATION))
            .signWith(REFRESH_SECRET, SignatureAlgorithm.HS256)
            .compact()
    }


    private fun createHeader(): Map<String, Any> {
        val header: MutableMap<String, Any> = HashMap()
        header["typ"] = "JWT"
        header["alg"] = "HS256"
        return header
    }

    private fun createClaims(user: User): Map<String, Any?> {
        val claims: MutableMap<String, Any?> = HashMap()
        claims["Identifier"] = user.getIdentifier()
        claims["Role"] = user.getRole()
        return claims
    }
}

@RequiredArgsConstructor
@Getter
enum class TokenStatus {
    AUTHENTICATED,
    EXPIRED,
    INVALID
}

@RequiredArgsConstructor
@Getter
enum class JwtRule(val value: String) {
    JWT_ISSUE_HEADER("Set-Cookie"),
    JWT_RESOLVE_HEADER("Cookie"),
    ACCESS_PREFIX("access"),
    REFRESH_PREFIX("refresh");
}