package com.zhentao.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 org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * Token有效期：1小时
 */
@Component
public class JwtUtil {
    
    @Value("${jwt.secret:change_me_secret_key_for_admin}")
    private String secret;
    
    /**
     * Token过期时间：1小时（3600秒）
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000; // 1小时
    
    /**
     * 生成Token
     * 
     * @param userId 用户ID
     * @return Token字符串
     */
    public String generateToken(Integer userId) {
        Date now = new Date();
        Date expireAt = new Date(now.getTime() + EXPIRE_TIME);
        
        Algorithm algorithm = Algorithm.HMAC256(secret);
        
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        
        return JWT.create()
                .withHeader(header)
                .withClaim("userId", userId)
                .withIssuedAt(now)
                .withExpiresAt(expireAt)
                .sign(algorithm);
    }
    
    /**
     * 验证Token并获取用户ID
     * 
     * @param token Token字符串
     * @return 用户ID，如果Token无效则返回null
     */
    public Integer getUserIdFromToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("userId").asInt();
        } catch (JWTVerificationException e) {
            // Token无效或已过期
            return null;
        }
    }
    
    /**
     * 验证Token是否有效
     * 
     * @param token Token字符串
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }
    
    /**
     * 检查Token是否即将过期（剩余时间少于5分钟）
     * 
     * @param token Token字符串
     * @return 是否即将过期
     */
    public boolean isTokenExpiringSoon(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Date expiresAt = jwt.getExpiresAt();
            if (expiresAt == null) {
                return true;
            }
            long remainingTime = expiresAt.getTime() - System.currentTimeMillis();
            return remainingTime < 5 * 60 * 1000; // 少于5分钟
        } catch (Exception e) {
            return true;
        }
    }
}

