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

/**
 * 获取tGit上某分支生命周期
 * @param {object} options 输入配置
 * @param {string} options.projectName 项目名称
 * @param {string} options.branchName 分支名称
 * @param {string} options.privateToken 密钥
 * @returns {Promise<object>} 请求Promise
 * @example
 *
 * getBranchLifeCycle({
 *   projectName: 't-comm',
 *   branchName: 'master',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function getBranchLifeCycle(_ref) {
  var projectName = _ref.projectName,
    branchName = _ref.branchName,
    privateToken = _ref.privateToken,
    _ref$baseUrl = _ref.baseUrl,
    baseUrl = _ref$baseUrl === void 0 ? T_GIT_BASE_URL : _ref$baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName || !branchName) {
      return;
    }
    var url = "/api/v3/projects/".concat(encodeURIComponent(projectName), "/tloc/branch/lifecycle");
    url = resolveBaseUrl(baseUrl || '', url);
    instance({
      url: url,
      method: 'GET',
      params: {
        branch_name: branchName
      },
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 获取默认分支
 * @param {object} options 输入配置
 * @param {string} options.projectName 项目名称
 * @param {string} options.privateToken 密钥
 * @returns {Promise<string>} 请求Promise
 * @example
 *
 * getProjectDefaultBranch({
 *   projectName: 't-comm',
 *   privateToken: 'xxxxx',
 * }).then((branch) => {
 *  console.log('branch: ', branch)
 * })
 */
function getProjectDefaultBranch(_ref2) {
  var projectName = _ref2.projectName,
    privateToken = _ref2.privateToken,
    _ref2$baseUrl = _ref2.baseUrl,
    baseUrl = _ref2$baseUrl === void 0 ? T_GIT_BASE_URL : _ref2$baseUrl;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var detail, getMainBranch, branch;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          getMainBranch = function _getMainBranch() {
            return detail.default_branch || '';
          };
          _context.next = 1;
          return getOneProjectDetail({
            projectName: projectName,
            privateToken: privateToken,
            baseUrl: baseUrl
          });
        case 1:
          detail = _context.sent;
          branch = getMainBranch();
          return _context.abrupt("return", branch);
        case 2:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 获取仓库的分支列表
 * @param {object} options 输入配置
 * @param {string} options.projectName 项目名称
 * @param {string} options.privateToken 密钥
 * @param {string} options.baseUrl baseUrl
 * @returns {Promise<Array<object>>} 请求Promise
 * @example
 *
 * getBranchesByProjectName({
 *   projectName: 't-comm',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function getBranchesByProjectName(_ref3) {
  var projectName = _ref3.projectName,
    privateToken = _ref3.privateToken,
    _ref3$baseUrl = _ref3.baseUrl,
    baseUrl = _ref3$baseUrl === void 0 ? T_GIT_BASE_URL : _ref3$baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName) {
      reject('No ProjectName');
      return;
    }
    instance({
      url: resolveBaseUrl(baseUrl, "/api/v3/projects/".concat(encodeURIComponent(projectName), "/repository/branches")),
      method: 'GET',
      params: {
        per_page: 100
      },
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 获取分支详情
 * @param {object} options 输入配置
 * @param {string} options.projectName 项目名称
 * @param {string} options.branchName 分支名称
 * @param {string} options.privateToken 密钥
 * @returns {Promise<object>} 请求Promise
 * @example
 *
 * getOneBranchDetail({
 *   projectName: 't-comm',
 *   branchName: 'master',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function getOneBranchDetail(_ref4) {
  var projectName = _ref4.projectName,
    branchName = _ref4.branchName,
    privateToken = _ref4.privateToken,
    baseUrl = _ref4.baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName || !branchName) {
      return;
    }
    var url = "/api/v3/projects/".concat(encodeURIComponent(projectName), "/repository/branches/").concat(encodeURIComponent(branchName));
    url = resolveBaseUrl(baseUrl, url);
    instance({
      url: url,
      method: 'GET',
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 合并分支：将分支或者 commit 合并到指定分支
 *
 * 对应工蜂 API：PUT /api/v3/projects/:id/repository/branches/merge
 *
 * @param {object} options 输入配置
 * @param {number | string} options.id 项目 ID 或 项目全路径 project_full_path
 * @param {string} options.sourceObjectId 源分支名或者 commit
 * @param {string} options.targetBranch 目标分支名
 * @param {number} [options.sourceProjectId] 源项目 ID，默认为 id 的值
 * @param {'merge' | 'rebase' | 'squash'} [options.mergeType] 合并方式，默认为普通合并 merge
 * @param {string} [options.commitMessage] 合并点提交信息（mergeType=rebase 时必填）
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<unknown>} 请求 Promise
 * @example
 *
 * mergeBranches({
 *   id: 12345,
 *   sourceObjectId: 'feature/xxx',
 *   targetBranch: 'master',
 *   mergeType: 'merge',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function mergeBranches(_ref5) {
  var id = _ref5.id,
    sourceObjectId = _ref5.sourceObjectId,
    targetBranch = _ref5.targetBranch,
    sourceProjectId = _ref5.sourceProjectId,
    mergeType = _ref5.mergeType,
    commitMessage = _ref5.commitMessage,
    privateToken = _ref5.privateToken,
    baseUrl = _ref5.baseUrl;
  return new Promise(function (resolve, reject) {
    if (id === undefined || id === null || id === '' || !sourceObjectId || !targetBranch) {
      reject(new Error('id, sourceObjectId, targetBranch is required'));
      return;
    }
    var encodedId = typeof id === 'string' ? encodeURIComponent(id) : id;
    var url = "/api/v3/projects/".concat(encodedId, "/repository/branches/merge");
    url = resolveBaseUrl(baseUrl, url);
    var data = {
      source_object_id: sourceObjectId,
      target_branch: targetBranch
    };
    if (sourceProjectId !== undefined) {
      data.source_project_id = sourceProjectId;
    }
    if (mergeType !== undefined) {
      data.merge_type = mergeType;
    }
    if (commitMessage !== undefined) {
      data.commit_message = commitMessage;
    }
    instance({
      url: url,
      method: 'PUT',
      data: data,
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 创建新分支
 *
 * 对应工蜂 API：POST /api/v3/projects/:id/repository/branches
 *
 * @param {object} options 输入配置
 * @param {string | number} options.projectName 项目名称或项目 ID
 * @param {string} options.branchName 新分支名
 * @param {string} options.ref 基于哪个分支/commit/tag 创建
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<{ name: string } & Record<string, unknown>>} 新建分支信息
 * @example
 *
 * createBranch({
 *   projectName: 'group/sub/repo',
 *   branchName: 'feature/x',
 *   ref: 'master',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function createBranch(_ref6) {
  var projectName = _ref6.projectName,
    branchName = _ref6.branchName,
    ref = _ref6.ref,
    privateToken = _ref6.privateToken,
    baseUrl = _ref6.baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName || !branchName || !ref) {
      reject(new Error('projectName, branchName, ref is required'));
      return;
    }
    // 清洗 ref：去除首尾空白和尾部斜杠，防止工蜂 404
    var cleanRef = ref.trim().replace(/\/+$/, '');
    var url = resolveBaseUrl(baseUrl, "/api/v3/projects/".concat(encodeProject(projectName), "/repository/branches"));
    instance({
      url: url,
      method: 'POST',
      data: {
        branch_name: branchName,
        ref: cleanRef
      },
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 删除分支
 *
 * 对应工蜂 API：DELETE /api/v3/projects/:id/repository/branches/:branch
 *
 * @param {object} options 输入配置
 * @param {string | number} options.projectName 项目名称或项目 ID
 * @param {string} options.branchName 要删除的分支名
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<unknown>} 请求 Promise
 * @example
 *
 * deleteBranch({
 *   projectName: 'group/sub/repo',
 *   branchName: 'feature/x',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function deleteBranch(_ref7) {
  var projectName = _ref7.projectName,
    branchName = _ref7.branchName,
    privateToken = _ref7.privateToken,
    baseUrl = _ref7.baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName || !branchName) {
      reject(new Error('projectName, branchName is required'));
      return;
    }
    var url = resolveBaseUrl(baseUrl, "/api/v3/projects/".concat(encodeProject(projectName), "/repository/branches/").concat(encodeURIComponent(branchName)));
    instance({
      url: url,
      method: 'DELETE',
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}
/**
 * 修改分支
 *
 * 编辑给定项目的某个分支。注意：如果项目内已存在 Mainline 分支，则不允许将其他分支设置成 Mainline 类别。
 *
 * 对应工蜂 API：PUT /api/v3/projects/:id/repository/branches/:branch
 *
 * @param {object} options 输入配置
 * @param {string | number} options.projectName 项目 ID 或项目全路径 project_full_path
 * @param {string} options.branchName 分支名
 * @param {string} [options.description] 分支描述
 * @param {string} [options.branchType] 分支类别，比如 Mainline、Feature、Others 等
 * @param {string} options.privateToken 密钥
 * @param {string} [options.baseUrl] baseUrl
 * @returns {Promise<{ name: string } & Record<string, unknown>>} 修改后的分支信息
 * @example
 *
 * editBranch({
 *   projectName: 'group/sub/repo',
 *   branchName: 'feature/x',
 *   branchType: 'Feature',
 *   description: 'feature 分支',
 *   privateToken: 'xxxxx',
 * }).then((resp) => {
 *
 * })
 */
function editBranch(_ref8) {
  var projectName = _ref8.projectName,
    branchName = _ref8.branchName,
    description = _ref8.description,
    branchType = _ref8.branchType,
    privateToken = _ref8.privateToken,
    baseUrl = _ref8.baseUrl;
  return new Promise(function (resolve, reject) {
    if (!projectName || !branchName) {
      reject(new Error('projectName, branchName is required'));
      return;
    }
    var url = resolveBaseUrl(baseUrl, "/api/v3/projects/".concat(encodeProject(projectName), "/repository/branches/").concat(encodeURIComponent(branchName)));
    var data = {
      branch: branchName
    };
    if (description !== undefined) {
      data.description = description;
    }
    if (branchType !== undefined) {
      data.branch_type = branchType;
    }
    instance({
      url: url,
      method: 'PUT',
      data: data,
      headers: {
        'PRIVATE-TOKEN': privateToken
      }
    }).then(function (res) {
      resolve(res.data);
    })["catch"](function (err) {
      reject(err);
    });
  });
}

export { createBranch, deleteBranch, editBranch, getBranchLifeCycle, getBranchesByProjectName, getOneBranchDetail, getProjectDefaultBranch, mergeBranches };
