package com.it.rattan.monisuo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    /** 密钥 */
    private static final String SECRET = "monisuo_jwt_secret_key_2024";
    /** 过期时间(7天) */
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000L;
    /** 签发者 */
    private static final String ISSUER = "monisuo";

    /**
     * 生成Token
     */
    public static String createToken(Long userId, String username, String type) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + EXPIRE_TIME);

        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");

        return JWT.create()
                .withHeader(header)
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(expireDate)
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("type", type)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证Token
     */
    public static DecodedJWT verifyToken(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET))
                .withIssuer(ISSUER)
                .build();
        return verifier.verify(token);
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT jwt = verifyToken(token);
            return jwt.getClaim("userId").asLong();
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 获取用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = verifyToken(token);
            return jwt.getClaim("username").asString();
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 获取类型(user/admin)
     */
    public static String getType(String token) {
        try {
            DecodedJWT jwt = verifyToken(token);
            return jwt.getClaim("type").asString();
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    /**
     * 检查Token是否有效
     */
    public static boolean isValid(String token) {
        try {
            verifyToken(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }
}
