import axios from 'axios';
import { flatten } from '../list/flat.mjs';
import '@babel/runtime/helpers/toConsumableArray';
import '@babel/runtime/helpers/typeof';
import { BASE_URL } from './helper/helper.mjs';
import { fetchRainbowConfigFromSdk } from './sdk.mjs';
import '../json/json-parse.mjs';

/**
 * 拉取七彩石配置
 * @param {String} key 七彩石的key
 * @param {object} secretInfo 密钥信息
 * @param {string} secretInfo.appId 项目Id
 * @param {string} secretInfo.envName 环境
 * @param {string} secretInfo.groupName 组名称
 * @returns {Promise<object>} 请求Promise
 *
 * @example
 *
 * fetchRainbowConfig('test', {
 *   appId: 'xx',
 *   envName: 'prod',
 *   groupName: 'robot',
 * }).then((resp) => {
 *   console.log(resp)
 * });
 *
 */
function fetchRainbowConfig(key, secretInfo, options) {
  var _a;
  var appID = secretInfo.appID,
    appId = secretInfo.appId,
    envName = secretInfo.envName,
    groupName = secretInfo.groupName,
    userId = secretInfo.userId,
    userID = secretInfo.userID,
    secretKey = secretInfo.secretKey;
  if ((userId || userID) && secretKey && (options === null || options === void 0 ? void 0 : options.sdk)) {
    return fetchRainbowConfigFromSdk({
      secretInfo: secretInfo,
      sdk: options.sdk,
      key: key,
      initOptions: options === null || options === void 0 ? void 0 : options.initOptions,
      isFetchGroup: options === null || options === void 0 ? void 0 : options.isFetchGroup,
      tryJsonParse: (_a = options === null || options === void 0 ? void 0 : options.tryJsonParse) !== null && _a !== void 0 ? _a : false
    });
  }
  return new Promise(function (resolve, reject) {
    axios({
      url: "".concat(BASE_URL, "/config.v2.ConfigService/PullConfigReq"),
      method: 'POST',
      data: {
        pull_item: {
          app_id: appId || appID,
          group: groupName,
          envName: envName
        }
      }
    }).then(function (res) {
      var _a;
      if (res.data.ret_code) {
        reject(res.data);
        return;
      }
      var keyValues = res.data.config.items[0].key_values;
      var flattenValues = flatten(keyValues, 'key');
      var resData = (_a = flattenValues[key]) === null || _a === void 0 ? void 0 : _a.value;
      resolve(resData);
    })["catch"](function (err) {
      reject(err);
    });
  });
}

export { fetchRainbowConfig };
