package com.rera.mss.security

import io.jsonwebtoken.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Component
import java.lang.Exception
import java.util.*

@Component
class JwtTokenProvider {

    private val logger: Logger = LoggerFactory.getLogger(JwtTokenProvider::class.java)

    @Value("\${app.jwtSecret}")
    private lateinit var jwtSecret: String
    @Value("\${app.jwtExpirationInMs}")
    private var jwtExpirationInMs: Int = 0


    fun generateToken(authentication: Authentication): String {
        val userPrincipal: UserPrincipal = authentication.principal as UserPrincipal

        val now = Date()
        val expiryDate = Date(now.time + jwtExpirationInMs)

        return Jwts.builder()
                .setSubject(userPrincipal.getId().toString())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact()
    }

    fun getUserIdFromJwt(token: String): Long {
        val claims: Claims = Jwts.parser()
                .setSigningKey(jwtSecret)
                .parseClaimsJws(token)
                .body

        return claims.subject.toLong()
    }

    fun validateToken(authToken: String): Boolean {
        return try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken)
            true
        } catch (e: Exception) {
            when (e) {
                is SignatureException -> logger.error("Invalid JWT signature", e)
                is MalformedJwtException -> logger.error("Invalid JWT token", e)
                is ExpiredJwtException -> logger.error("Expired JWT token", e)
                is UnsupportedJwtException -> logger.error("Unsupported JWT token", e)
                is IllegalArgumentException -> logger.error("JWT claims string is empty", e)
            }
            false
        }

    }

}