package com.usky.vpp.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.common.core.exception.BusinessException;
import org.springframework.util.StringUtils;

/**
 * 运管平台 UN/DN 国密 HTTP 载荷解析（application/json 下密文常为 JSON 字符串）。
 */
public final class VppUnCipherPayloadHelper {

    private VppUnCipherPayloadHelper() {
    }

    /**
     * 从 HTTP body 提取 Base64 密文。
     * <ul>
     *   <li>JSON 字符串：{@code "MIIB..."}</li>
     *   <li>裸 Base64：{@code MIIB...}</li>
     * </ul>
     */
    public static String extractCipherPayload(String body, ObjectMapper objectMapper) {
        if (!StringUtils.hasText(body)) {
            return "";
        }
        String trimmed = body.trim();
        if (trimmed.startsWith("\"")) {
            try {
                return objectMapper.readValue(trimmed, String.class);
            } catch (Exception ex) {
                throw new BusinessException("密文 JSON 字符串解析失败: " + ex.getMessage());
            }
        }
        return trimmed;
    }

    /** 将 Base64 密文包装为合法 JSON 字符串请求体。 */
    public static String wrapCipherPayload(String cipherBase64, ObjectMapper objectMapper) {
        try {
            return objectMapper.writeValueAsString(cipherBase64);
        } catch (Exception ex) {
            throw new BusinessException("密文 JSON 包装失败: " + ex.getMessage());
        }
    }
}
