



package com.example.spring_auth.util

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.SignatureException
import java.util.*
import javax.crypto.spec.SecretKeySpec

object JwtUtil {
    private const val SECRET_KEY = "abcdefghijklmnopqrstuvwyz0123456789" // Replace with a strong secret key
    private const val EXPIRATION_TIME = 3600000L // Token validity: 1 hour

    private val key = SecretKeySpec(SECRET_KEY.toByteArray(), SignatureAlgorithm.HS256.jcaName)

    fun validateTokenAndGetSubject(token: String): String {
        return try {
            //val claims: Claims = Jwts.parserBuilder()
            val claims: Claims = Jwts.parser()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .body
            claims.subject
        } catch (e: SignatureException) {
            throw RuntimeException("Invalid token")
        }
    }

    fun generateToken(email: String): String {
        val now = Date()
        val expiryDate = Date(now.time + EXPIRATION_TIME)

        //println("Expiration date: $expiryDate")

        return Jwts.builder()
            .subject(email)
            .issuedAt(now)
            .expiration(expiryDate)
            .signWith(key, SignatureAlgorithm.HS256)
            .compact()
    }
}
