package org.dromara.system.zwy.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.zwy.properties.HmacProperties;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class HmacClient {

    private final HmacProperties properties;
    private final HmacTokenClient hmacTokenClient;
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public String calculateHmac(String base64PlainText) {
        try {
            if (base64PlainText == null) {
                log.warn("待加密原文为空！");
            }

            if (properties.getServerUrl() == null || properties.getAppId() == null ||
                properties.getSecretKey() == null || properties.getKeyLabel() == null) {
                throw new IllegalStateException("HMAC配置项缺失，请检查配置文件");
            }
            String url = properties.getServerUrl() + "/sign/v1/hmac";
            String appId = properties.getAppId();
            String timestamp = String.valueOf(System.currentTimeMillis());
            String nonce = UUID.randomUUID().toString().replaceAll("-", "");

            Map<String, String> body = Map.of(
                "keyLabel", properties.getKeyLabel(),
                "plainText", base64PlainText
            );
            String gateWayToken = hmacTokenClient.getAppToken();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("appId", appId);
            headers.add("timestamp", timestamp);
            headers.add("nonce", nonce);
            headers.add("gateWayToken", gateWayToken);
            HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String responseBody = response.getBody();
            JsonNode json = objectMapper.readTree(responseBody);
            String code = json.path("code").asText();
            if (!"0".equals(code)) {
                String msg = json.path("msg").asText();
                log.error("HMAC计算失败: " + msg);
            }
            String hmac = json.path("data").asText();
            return hmac;

        } catch (Exception e) {
            log.error("HMAC服务调用异常:{}", e.getMessage());
            e.printStackTrace();
        }
    return null;
    }
}
