package org.xyzh.auth.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xyzh.common.core.domain.LoginDomain;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.utils.IDUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description    JwtTokenUtil.java文件描述 JWT工具类
 * @filename    JwtTokenUtil.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Component
public class JwtTokenUtil {

    @Value("${school-news.auth.jwt-secret:schoolNewsDefaultSecretKeyForJWT2025}")
    private String secret;

    @Value("${school-news.auth.jwt-expiration:86400}")
    private Long expiration;

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    /**
     * @description    生成JWT令牌
     * @param    loginDomain 登录域对象
     * @return    String JWT令牌
     * @author    yslg
     * @since 2025-09-28
     */
    public String generateToken(LoginDomain loginDomain) {
        Map<String, Object> claims = new HashMap<>();
        TbSysUser user = loginDomain.getUser();
        
        claims.put("userId", user.getID());
        claims.put("username", user.getUsername());
        claims.put("email", user.getEmail());
        claims.put("loginType", loginDomain.getLoginType());
        claims.put("ipAddress", loginDomain.getIpAddress());

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getID())
                .setId(IDUtils.generateID())  // 使用IDUtils生成JWT ID
                .setIssuedAt(new Date())
                .setExpiration(generateExpirationDate())
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * @description    从令牌中获取用户ID
     * @param    token JWT令牌
     * @return    String 用户ID
     * @author    yslg
     * @since 2025-09-28
     */
    public String getUserIdFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * @description    从令牌中获取过期时间
     * @param    token JWT令牌
     * @return    Date 过期时间
     * @author    yslg
     * @since 2025-09-28
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * @description    从令牌中获取指定信息
     * @param    token JWT令牌
     * @param    claimsResolver 信息解析器
     * @return    T 指定信息
     * @author    yslg
     * @since 2025-09-28
     */
    public <T> T getClaimFromToken(String token, java.util.function.Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * @description    从令牌中获取所有信息
     * @param    token JWT令牌
     * @return    Claims 所有信息
     * @author    yslg
     * @since 2025-09-28
     */
    public Claims getAllClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * @description    验证令牌
     * @param    token JWT令牌
     * @param    userId 用户ID
     * @return    boolean 是否有效
     * @author    yslg
     * @since 2025-09-28
     */
    public boolean validateToken(String token, String userId) {
        try {
            final String tokenUserId = getUserIdFromToken(token);
            return (userId.equals(tokenUserId) && !isTokenExpired(token));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @description    检查令牌是否过期
     * @param    token JWT令牌
     * @return    boolean 是否过期
     * @author    yslg
     * @since 2025-09-28
     */
    public boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * @description    生成过期时间
     * @return    Date 过期时间
     * @author    yslg
     * @since 2025-09-28
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }
}
