package com.zhentao.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
public class JwtUtil {

    @Value("${jwt.secret:change_me_secret}")
    private String secret;

    @Value("${jwt.expireMinutes:1440}")
    private long expireMinutes; // 默认一天

    public String generateToken(Map<String, Object> claims) {
        Date now = new Date();
        Date expireAt = new Date(now.getTime() + expireMinutes * 60 * 1000);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        com.auth0.jwt.JWTCreator.Builder builder = JWT.create()
                .withIssuedAt(now)
                .withExpiresAt(expireAt);
        if (claims != null) {
            claims.forEach((k, v) -> {
                if (v instanceof Integer) builder.withClaim(k, (Integer) v);
                else if (v instanceof Long) builder.withClaim(k, (Long) v);
                else if (v instanceof Boolean) builder.withClaim(k, (Boolean) v);
                else if (v instanceof Double) builder.withClaim(k, (Double) v);
                else builder.withClaim(k, String.valueOf(v));
            });
        }
        return builder.sign(algorithm);
    }
}