package com.izouma.nineth.utils;

import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.core.exception.FailureCode;
import com.izouma.nineth.exception.BusinessException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

public class AdapayUtils {
    public static String packageRequestUrl(Map<String, Object> requestParams) throws BaseAdaPayException {
        String adapayFuncCode = (String) requestParams.get("adapay_func_code");
        if (StringUtils.isBlank(adapayFuncCode)) {
            throw new BaseAdaPayException(FailureCode.ADAPAY_FUNC_CODE_NOT_BLANK.getFailureCode());
        }
        String adapayApiVersion = (String) requestParams.getOrDefault("adapay_api_version", "v1");
        return "/" + adapayApiVersion + "/" + StringUtils.replace(adapayFuncCode, ".", "/");
    }

    public static void checkSuccess(Map<String, Object> map) {
        if (!"succeeded".equals(MapUtils.getString(map, "status"))) {
            String errMsg = MapUtils.getString(map, "error_msg");
            String errCode = MapUtils.getString(map, "error_code");
            throw new BusinessException(errMsg + "(" + errCode + ")");
        }
    }
}
