import axios from 'axios';
import { getCrypto } from '../nodejs/crypto.mjs';

var URL_MAP = {
  ACCESS_TOKEN: 'https://api.weixin.qq.com/cgi-bin/token',
  TICKET: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
};
var sha1 = function sha1(content) {
  return getCrypto().createHash('sha1').update(content).digest('hex');
};
function getAccessToken(_ref) {
  var appId = _ref.appId,
    appSecret = _ref.appSecret;
  return new Promise(function (resolve, reject) {
    axios({
      url: "".concat(URL_MAP.ACCESS_TOKEN, "?grant_type=client_credential&appid=").concat(appId, "&secret=").concat(appSecret)
    }).then(function (res) {
      resolve(res.data || {});
    })["catch"](function (err) {
      reject(err);
    });
  });
}
function getAPITicket(accessToken) {
  return new Promise(function (resolve, reject) {
    axios({
      url: "".concat(URL_MAP.TICKET, "?access_token=").concat(accessToken, "&type=jsapi")
    }).then(function () {
      var res = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      resolve(res.data || {});
    })["catch"](function (err) {
      reject(err);
    });
  });
}
function getNonceStr() {
  var buf = getCrypto().randomBytes(12);
  var hexToDec = buf.toString('hex');
  return hexToDec;
}
/**
 * 获取jsAPI签名
 *
 * 校验地址：https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
 *
 * 文档地址：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
 * @param {string} ticket 票据
 * @param {string} url 当前url，不包括#之后的部分
 * @returns signature
 * @example
 * ```ts
 * const sig = genSignature('jsapi_ticket_xxx', 'https://example.com/page');
 * // {
 * //   timestamp: 1700000000,
 * //   nonceStr: 'random-12-bytes-hex',
 * //   signature: 'sha1-hex-string',
 * //   url: 'https://example.com/page',
 * // }
 * ```
 */
function genSignature(ticket, url) {
  var timestamp = Math.floor(Date.now() / 1000);
  var nonceStr = getNonceStr();
  var list = ["jsapi_ticket=".concat(ticket), "noncestr=".concat(nonceStr), "timestamp=".concat(timestamp), "url=".concat(url)];
  var str = list.join('&');
  var signature = sha1(str);
  return {
    timestamp: timestamp,
    nonceStr: nonceStr,
    signature: signature,
    url: url
  };
}

export { genSignature, getAPITicket, getAccessToken };
