const axios = require('../../axios');

/**
 * Remove `v` prefix from version tags.
 */
function normalizeVersionTag(version = undefined) {
  if (version && version.toLowerCase().substr(0, 1) === 'v') {
    return version.substr(1);
  }

  return version;
}

/**
 * @param {string} host
 * @param {string} pluginId
 * @param {string} fileId
 * @param {string} token
 * @param {string=} version
 * @returns {Promise<*>}
 */
function deployRelease(host, pluginId, fileId, token, version = undefined) {
  return axios.post(
    `https://api.${host}/webapp_plugins/${pluginId}/code`,
    {
      file_id: fileId,
      version: normalizeVersionTag(version),
    },
    {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    },
  );
}

module.exports = deployRelease;
