package com.nbport.zgwl.contractpush.handler;

import cn.hutool.core.util.StrUtil;
import com.nbport.zgwl.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 推送请求加工器
 * 这里只做最基础的 token、sys_code、时间戳补全，保持逻辑简单
 */
@Component
public class ContractPushRequestHandler {

    /** 复制 payload 副本，避免修改原始对象 */
    public Map<String, Object> copyPayload(Map<String, Object> payload) {
        return payload == null ? new LinkedHashMap<>() : new LinkedHashMap<>(payload);
    }

    /** 补全结算平台请求体：body 中加入 token */
    public Map<String, Object> prepareSettlementPayload(Map<String, Object> payload, String token) {
        Map<String, Object> requestBody = copyPayload(payload);
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("结算平台 token 不能为空");
        }
        requestBody.put("token", token);
        return requestBody;
    }

    /** 补全数据采集请求体：body 中加入 sys_code 和 timeStamp */
    public Map<String, Object> prepareDataCollectionPayload(Map<String, Object> payload, String sysCode) {
        Map<String, Object> requestBody = copyPayload(payload);
        if (StrUtil.isBlank(sysCode)) {
            throw new ServiceException("数据采集 sysCode 未配置");
        }
        requestBody.put("sys_code", sysCode);
        requestBody.putIfAbsent("timeStamp", String.valueOf(System.currentTimeMillis()));
        return requestBody;
    }

    /** 构建数据采集请求头：cj_token 必填，systemKey 按需携带 */
    public Map<String, String> buildDataCollectionHeaders(String token, String systemKey, boolean includeSystemKey) {
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("数据采集 cj_token 不能为空");
        }
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("cj_token", token);
        if (includeSystemKey) {
            headers.put("systemKey", systemKey);
        }
        return headers;
    }
}
