package cn.qihangerp.service.external.pdd;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 拼多多 POP 签名：md5(client_secret + sorted_key_value_concat + client_secret) 大写。
 *
 * @author guochengyu
 */
public final class PddPopSignUtil {

    private PddPopSignUtil() {
    }

    public static String sign(Map<String, String> params, String clientSecret) {
        TreeMap<String, String> sorted = new TreeMap<>();
        for (Map.Entry<String, String> e : params.entrySet()) {
            if (e.getKey() == null || "sign".equalsIgnoreCase(e.getKey())) {
                continue;
            }
            if (e.getValue() == null || e.getValue().isEmpty()) {
                continue;
            }
            sorted.put(e.getKey(), e.getValue());
        }
        StringBuilder sb = new StringBuilder();
        sb.append(clientSecret);
        for (Map.Entry<String, String> e : sorted.entrySet()) {
            sb.append(e.getKey()).append(e.getValue());
        }
        sb.append(clientSecret);
        return md5Upper(sb.toString());
    }

    private static String md5Upper(String raw) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] dig = md.digest(raw.getBytes(StandardCharsets.UTF_8));
            StringBuilder hex = new StringBuilder();
            for (byte b : dig) {
                String h = Integer.toHexString(b & 0xff);
                if (h.length() == 1) {
                    hex.append('0');
                }
                hex.append(h);
            }
            return hex.toString().toUpperCase();
        } catch (Exception e) {
            throw new IllegalStateException("MD5 sign failed", e);
        }
    }
}
