package com.crm.ucard.util;

import com.alibaba.fastjson.JSON;
import com.crm.rely.backend.util.HttpUtil;
import com.crm.ucard.config.VaultodyConfig;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class VaultodyUtil {

    public static Connection.Response post(Map<String, Object> paramMap, String requestPath, VaultodyConfig config) {
        Connection.Response response = null;
        try {
            // POST JSON body
            String body = JSON.toJSONString(paramMap);
            String query = "{}"; // POST 时 query 通常为空，否则按接口要求填写

            // ------------------ 时间戳（秒） ------------------
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

            // ------------------ 构建消息用于签名 ------------------
            String message = timestamp + config.getMethod() + requestPath + body + query;

            String signature = getSignature(message, config.getApiSecret());
            System.out.println("Signature: " + signature);
            Map<String, String> headers = new HashMap<>();
            headers.put("x-api-key", config.getApiKey());
            headers.put("x-api-sign", signature);
            headers.put("x-api-timestamp", timestamp);
            headers.put("x-api-passphrase", config.getPassphrase());
            headers.put("Content-Type", "application/json");
            log.info("Vaultody sendRequest--url:{},headers ：{}, body: {}", config.getBaseUrl() + requestPath, headers, body);
            response = HttpUtil.post(config.getBaseUrl() + requestPath, headers, body);
            log.info("Vaultody sendPostJson url {}, response: {}", config.getBaseUrl() + requestPath, response.body());
        } catch (Exception e) {
            log.error("exception", e);
        }
        return response;

    }

    public static String getSignature(String message, String apiSecret) {
        try {
            byte[] decodedSecret = Base64.getDecoder().decode(apiSecret);
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodedSecret, "HmacSHA256");
            mac.init(secretKeySpec);
            byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));

            return Base64.getEncoder().encodeToString(hash);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

