package com.usky.vpp.client;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.common.core.exception.BusinessException;
import com.usky.vpp.util.VppUnPayloadHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * UN 平台 JSON 客户端
 */
@Component
public class VppUnClient {

    @Autowired
    private VppUnHttpExecutor httpExecutor;

    @Autowired
    private ObjectMapper objectMapper;

    public Map<String, Object> post(String serviceName, Map<String, Object> body, boolean withToken) {
        String raw = httpExecutor.postRaw(serviceName, body, withToken);
        try {
            Map<String, Object> response = objectMapper.readValue(raw, new TypeReference<Map<String, Object>>() {
            });
            assertSuccess(serviceName, response);
            return response;
        } catch (BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BusinessException("UN 响应解析失败: " + serviceName);
        }
    }

    private void assertSuccess(String serviceName, Map<String, Object> response) {
        Integer code = VppUnPayloadHelper.getInteger(response, "code");
        if (code != null && code >= 400) {
            Object description = response.get("description");
            throw new BusinessException("运管平台 " + serviceName + " 返回错误: " + description);
        }
    }
}
