package com.goldenchart.upbit;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 업비트 Open API JWT (query_hash + HS512).
 */
public final class UpbitJwtSigner {

    private UpbitJwtSigner() {}

    public static String sign(String accessKey, String secretKey, Map<String, String> params) {
        String nonce = UUID.randomUUID().toString();
        var builder = JWT.create()
                .withClaim("access_key", accessKey)
                .withClaim("nonce", nonce);

        if (params != null && !params.isEmpty()) {
            String query = params.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .map(e -> e.getKey() + "=" + e.getValue())
                    .collect(Collectors.joining("&"));
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-512");
                byte[] digest = md.digest(query.getBytes(java.nio.charset.StandardCharsets.UTF_8));
                String queryHash = String.format("%0128x", new BigInteger(1, digest));
                builder.withClaim("query_hash", queryHash);
                builder.withClaim("query_hash_alg", "SHA512");
            } catch (Exception e) {
                throw new IllegalStateException("query_hash 생성 실패", e);
            }
        }

        return builder.sign(Algorithm.HMAC512(secretKey));
    }

    /** GET 등 쿼리 파라미터 없는 요청 */
    public static String signNoQuery(String accessKey, String secretKey) {
        return sign(accessKey, secretKey, null);
    }
}
