import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { resolveBaseUrl, instance } from './helper.mjs';
import 'axios';

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/**
 * 根据用户 ID 获取工蜂用户信息
 *
 * 对应工蜂 API：GET /api/v3/users/:id
 *
 * 应用场景：Webhook payload 中 `author.username` 可能不是标准 RTX，
 * 此时可以通过 `author_id` 反查拿到准确的 username。
 *
 * @param {object} options 输入配置
 * @param {number | string} options.userId 用户 ID
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<TGitUser | null>} 用户信息，失败或缺字段返回 null
 * @example
 *
 * getUserById({
 *   userId: 12345,
 *   privateToken: 'xxxxx',
 * }).then((user) => {
 *   console.log(user?.username);
 * })
 */
function getUserById(_ref) {
  var userId = _ref.userId,
    privateToken = _ref.privateToken,
    baseUrl = _ref.baseUrl;
  return new Promise(function (resolve) {
    if (!userId) {
      resolve(null);
      return;
    }
    var url = resolveBaseUrl(baseUrl, "/api/v3/users/".concat(userId));
    instance({
      url: url,
      method: 'GET',
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      var user = res.data;
      resolve((user === null || user === void 0 ? void 0 : user.username) ? user : null);
    })["catch"](function () {
      resolve(null);
    });
  });
}
/**
 * 根据用户名（英文名 / RTX）获取工蜂用户信息
 *
 * 对应工蜂 API：GET /api/v3/users?search=:username
 * 搜索接口可能返回多条结果，本函数会精确匹配 `username`，不命中返回 null。
 *
 * @param {object} options 输入配置
 * @param {string} options.username 用户名
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<number | null>} 用户 ID
 * @example
 *
 * getUserIdByUsername({
 *   username: 'novlan1',
 *   privateToken: 'xxxxx',
 * }).then((userId) => {
 *   console.log(userId); // 未命中返回 null
 * })
 */
function getUserIdByUsername(_ref2) {
  var username = _ref2.username,
    privateToken = _ref2.privateToken,
    baseUrl = _ref2.baseUrl;
  return new Promise(function (resolve) {
    if (!username) {
      resolve(null);
      return;
    }
    var url = resolveBaseUrl(baseUrl, '/api/v3/users');
    instance({
      url: url,
      method: 'GET',
      params: {
        search: username
      },
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      var users = res.data || [];
      var hit = users.find(function (u) {
        return u.username === username;
      });
      resolve(hit ? hit.id : null);
    })["catch"](function () {
      resolve(null);
    });
  });
}
/**
 * 批量将用户名列表转换为用户 ID 列表（跳过找不到的）
 *
 * @param {object} options 输入配置
 * @param {string[]} options.usernames 用户名数组
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<string[]>} 用户 ID 字符串数组（顺序与输入保持一致，跳过缺失项）
 * @example
 *
 * resolveUserIds({
 *   usernames: ['novlan1', 'someone'],
 *   privateToken: 'xxxxx',
 * }).then((ids) => {
 *   console.log(ids); // [ '1234', '5678' ]
 * })
 */
function resolveUserIds(_ref3) {
  var usernames = _ref3.usernames,
    privateToken = _ref3.privateToken,
    baseUrl = _ref3.baseUrl;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var ids, _iterator, _step, username, userId, _t;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          ids = [];
          _iterator = _createForOfIteratorHelper(usernames || []);
          _context.prev = 1;
          _iterator.s();
        case 2:
          if ((_step = _iterator.n()).done) {
            _context.next = 5;
            break;
          }
          username = _step.value;
          _context.next = 3;
          return getUserIdByUsername({
            username: username,
            privateToken: privateToken,
            baseUrl: baseUrl
          });
        case 3:
          userId = _context.sent;
          if (userId !== null) {
            ids.push(String(userId));
          }
        case 4:
          _context.next = 2;
          break;
        case 5:
          _context.next = 7;
          break;
        case 6:
          _context.prev = 6;
          _t = _context["catch"](1);
          _iterator.e(_t);
        case 7:
          _context.prev = 7;
          _iterator.f();
          return _context.finish(7);
        case 8:
          return _context.abrupt("return", ids);
        case 9:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 6, 7, 8]]);
  }));
}

export { getUserById, getUserIdByUsername, resolveUserIds };
