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

/**
 * 获取仓库详情
 * @param {object} options 输入配置
 * @param {string} options.projectName 项目名称
 * @param {string} options.privateToken 密钥
 * @returns {Promise<object>} 请求Promise
 * @example
 * getOneProjectDetail({
 *   projectName: 't-comm',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function getOneProjectDetail(_ref) {
  var projectName = _ref.projectName,
    privateToken = _ref.privateToken,
    baseUrl = _ref.baseUrl;
  var url = "/api/v3/projects/".concat(encodeURIComponent(projectName));
  url = resolveBaseUrl(baseUrl, url);
  return new Promise(function (resolve, reject) {
    instance({
      url: url,
      method: 'GET',
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 通过搜索获取一个项目信息
 * @param {object} options 输入配置
 * @param {string} options.search 搜索内容
 * @param {string} options.page 起始页码
 * @param {string} options.privateToken 密钥
 * @returns {Promise<Array<object>>} 请求Promise
 * @example
 *
 * getOneProjectBySearch({
 *   search: 't-comm',
 *   page: 1,
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function getOneProjectBySearch(_ref2) {
  var search = _ref2.search,
    privateToken = _ref2.privateToken,
    _ref2$page = _ref2.page,
    page = _ref2$page === void 0 ? 1 : _ref2$page,
    baseUrl = _ref2.baseUrl;
  return new Promise(function (resolve, reject) {
    var url = '/api/v3/projects';
    url = resolveBaseUrl(baseUrl, url);
    instance({
      url: url,
      method: 'GET',
      params: {
        per_page: 100,
        search: search,
        page: page
      },
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 获取某个token名下所有项目
 * @param {string} privateToken 密钥
 * @param {string} search 搜索内容
 * @returns {Array<object>} 项目列表
 * @example
 *
 * const projects = await getAllProjects('xxxxx');
 *
 * console.log(projects)
 */
function getAllProjects(privateToken) {
  var search = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var res, page, temp;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          res = [];
          page = 1; // eslint-disable-next-line no-constant-condition
        case 1:
          _context.next = 2;
          return getOneProjectBySearch({
            page: page,
            search: search,
            privateToken: privateToken
          });
        case 2:
          temp = _context.sent;
          res = res.concat(temp);
          page += 1;
          if (temp === null || temp === void 0 ? void 0 : temp.length) {
            _context.next = 3;
            break;
          }
          return _context.abrupt("continue", 4);
        case 3:
          _context.next = 1;
          break;
        case 4:
          return _context.abrupt("return", res);
        case 5:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 删除一个项目
 * @param {object} options 输入配置
 * @param {string} options.id 项目id
 * @param {string} options.privateToken 密钥
 * @returns {Promise<Array<object>>} 请求Promise
 * @example
 *
 * deleteTGitProject({
 *   id: '123'
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function deleteTGitProject(_ref3) {
  var id = _ref3.id,
    privateToken = _ref3.privateToken,
    baseUrl = _ref3.baseUrl;
  return new Promise(function (resolve, reject) {
    var url = "/api/v3/projects/".concat(encodeURIComponent(id));
    url = resolveBaseUrl(baseUrl, url);
    instance({
      url: url,
      method: 'DELETE',
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 解析工蜂项目的路径或完整 URL，提取出标准的 `group/sub/repo` 形式路径
 *
 * 支持的输入格式：
 *   - 完整 URL：           https://git.woa.com/pmd-mobile/pmd-h5/press-next
 *   - 带 .git 后缀：       https://git.woa.com/pmd-mobile/pmd-h5/press-next.git
 *   - SSH 地址：           git@git.woa.com:pmd-mobile/pmd-h5/press-next.git
 *   - 纯路径：             pmd-mobile/pmd-h5/press-next
 *   - 带首尾斜杠的路径：    /pmd-mobile/pmd-h5/press-next/
 *
 * @param {string} pathOrUrl 项目路径或 URL
 * @returns {string} 标准化后的项目路径（如 pmd-mobile/pmd-h5/press-next）
 * @example
 *
 * parseProjectPath('https://git.woa.com/pmd-mobile/pmd-h5/press-next.git')
 * // => 'pmd-mobile/pmd-h5/press-next'
 */
function parseProjectPath(pathOrUrl) {
  var projectPath = (pathOrUrl || '').trim();
  // 去掉 http(s):// 前缀 + host 部分（host 后第一个 / 之前的内容）
  projectPath = projectPath.replace(/^https?:\/\/[^/]+\//, '');
  // 兼容 SSH 形式 git@git.woa.com:group/sub/repo.git
  projectPath = projectPath.replace(/^git@[^:]+:/, '');
  // 去掉 .git 后缀
  projectPath = projectPath.replace(/\.git$/, '');
  // 去掉首尾斜杠
  projectPath = projectPath.replace(/^\/+|\/+$/g, '');
  return projectPath;
}
/**
 * 根据项目路径或 URL 获取项目信息（含 id / name / path_with_namespace）
 *
 * 本函数是 `parseProjectPath` + `getOneProjectDetail` 的便捷封装，
 * 支持与 `parseProjectPath` 相同的输入格式：
 *   - 完整 URL：           https://git.woa.com/pmd-mobile/pmd-h5/press-next
 *   - 带 .git 后缀：       https://git.woa.com/pmd-mobile/pmd-h5/press-next.git
 *   - SSH 地址：           git@git.woa.com:pmd-mobile/pmd-h5/press-next.git
 *   - 纯路径：             pmd-mobile/pmd-h5/press-next
 *
 * @param {object} options 输入配置
 * @param {string} options.pathOrUrl 项目路径或 URL
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<TGitProjectInfo>} 项目信息
 * @example
 *
 * getProjectByPath({
 *   pathOrUrl: 'https://git.woa.com/pmd-mobile/pmd-h5/press-next',
 *   privateToken: 'xxxxx',
 * }).then((info) => {
 *   console.log(info.id, info.path_with_namespace);
 * })
 */
function getProjectByPath(_ref4) {
  var pathOrUrl = _ref4.pathOrUrl,
    privateToken = _ref4.privateToken,
    baseUrl = _ref4.baseUrl;
  var projectName = parseProjectPath(pathOrUrl);
  return getOneProjectDetail({
    projectName: projectName,
    privateToken: privateToken,
    baseUrl: baseUrl
  });
}
/**
 * 创建一个项目
 *
 * 对应工蜂 OpenAPI：POST /api/v3/projects
 *
 * 注意：当 `namespace_id` 不为空时，需要用户拥有在指定命名空间中创建项目的权限。
 *
 * @param {object} options 输入配置
 * @param {CreateTGitProjectParams} options.data 创建项目的参数
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<TGitProjectInfo>} 新建项目的详情
 * @example
 *
 * createProject({
 *   data: {
 *     name: 'testapi',
 *     description: '测试项目',
 *     visibility_level: 0,
 *   },
 *   privateToken: 'xxxxx',
 * }).then((info) => {
 *   console.log(info.id, info.path_with_namespace);
 * });
 */
function createProject(_ref5) {
  var data = _ref5.data,
    privateToken = _ref5.privateToken,
    baseUrl = _ref5.baseUrl;
  var url = resolveBaseUrl(baseUrl, '/api/v3/projects');
  return new Promise(function (resolve, reject) {
    instance({
      url: url,
      method: 'POST',
      data: data,
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 修改项目设置
 *
 * 对应工蜂 OpenAPI：PUT /api/v3/projects/:id
 *
 * - 修改成功返回修改后的项目信息（{@link TGitProjectInfo}）
 * - 参数错误返回 400
 *
 * @param {object} options 输入配置
 * @param {string | number} options.id 项目 ID 或项目全路径（如 `group/sub/repo`）
 * @param {EditTGitProjectParams} options.data 修改项目的参数
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<TGitProjectInfo>} 修改后的项目详情
 * @example
 *
 * editProject({
 *   id: 32833,
 *   data: {
 *     name: 'testapp',
 *     review_enabled: true,
 *   },
 *   privateToken: 'xxxxx',
 * }).then((info) => {
 *   console.log(info.name);
 * });
 */
function editProject(_ref6) {
  var id = _ref6.id,
    data = _ref6.data,
    privateToken = _ref6.privateToken,
    baseUrl = _ref6.baseUrl;
  var url = resolveBaseUrl(baseUrl, "/api/v3/projects/".concat(encodeURIComponent(id)));
  return new Promise(function (resolve, reject) {
    instance({
      url: url,
      method: 'PUT',
      data: data,
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}

export { createProject, deleteTGitProject, editProject, getAllProjects, getOneProjectBySearch, getOneProjectDetail, getProjectByPath, parseProjectPath };
