package com.ruoyi.novel.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;


import java.nio.charset.StandardCharsets;
import java.util.Date;

// JwtUtil.java
public class JwtUtil {
    private static String SECRET = "your_jwt_secret_key";
    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        SECRET = secret;
    }

    private static final long EXPIRE = 86400; // 24小时
    public static String generateToken(Long userId) {
        Date now = new Date();
        Date expire = new Date(now.getTime() + EXPIRE * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId.toString())
                .setIssuedAt(now)
                .setExpiration(expire)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static boolean verifyToken(String token, Long userId) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();

            String subject = claims.getSubject();
            return userId.toString().equals(subject);
        } catch (Exception e) {
            return false;
        }
    }

    public static Long getUserIdFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
        return Long.parseLong(claims.getSubject());
    }

    // 补充Token解析方法
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }

    // 补充缺失的Token生成方法
//    public static String generateToken(Long userId) {
//        return Jwts.builder()
//                .setSubject(userId.toString())
//                .setExpiration(new Date(System.currentTimeMillis() + 86400 * 1000))
//                .signWith(SignatureAlgorithm.HS512, SECRET)
//                .compact();
//    }
}
