package com.datamate.gateway.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 网关侧JWT工具
 */
@Component
public class GatewayJwtUtils {
    private static final String DEFAULT_SECRET = "datamate-secret-key-for-jwt-token-generation";

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

    public Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public boolean validateToken(String token) {
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration != null && expiration.after(new Date());
    }

    public List<String> getStringListClaim(Claims claims, String claimName) {
        Object claimValue = claims.get(claimName);
        if (!(claimValue instanceof Collection<?> values)) {
            return Collections.emptyList();
        }
        return values.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
    }

    private SecretKey getSigningKey() {
        String secretValue = StringUtils.hasText(secret) ? secret : DEFAULT_SECRET;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] keyBytes = digest.digest(secretValue.getBytes(StandardCharsets.UTF_8));
            return Keys.hmacShaKeyFor(keyBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Cannot initialize JWT signing key", e);
        }
    }
}

