const base64 = require('base-64')
const fetch = require('node-fetch').default
const { logger } = require('./utils')

const organization = process.env.BITBUCKET_REPO_OWNER || 'viewdo';
const bitbucket_api = `https://api.bitbucket.org/2.0`;
const bitbucket_workspace_api = `${bitbucket_api}/workspaces/${organization}`
const bitbucket_repo_api = `${bitbucket_api}/repositories/${organization}`

const runPipeline = (user, password, repository, custom_build, branch = 'master') => {
  let target = {
    type: "pipeline_ref_target",
    ref_type: "branch",
    ref_name: branch
  }
  if (custom_build)
    target.selector = {
      type: "custom",
      pattern: custom_build
    }

  return fetch(`${bitbucket_repo_api}/${repository}/pipelines/`, {
    method: 'POST',
    body: JSON.stringify({
      target
    }),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
    }
  })
}

const setVariable = async (user, password, repository, key, value, secure) => {

  // If a repository isn't present, target the workspace
  // Note: repos use `_` and workspaces use `-` in url; repos require `/` after variables...
  const targetUrl = repository
    ? `${bitbucket_repo_api}/${repository}/pipelines_config/variables/`
    : `${bitbucket_workspace_api}/pipelines-config/variables`;

  // We need to retrieve all variables since we don't know the UUID for the token var
  // If we don't specify pagelen query param, it defaults to 10...max is 100
  let variable_list = await fetch(`${targetUrl}?pagelen=100`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
    }
  })
    .then(response => response.json())
    .then(r => r.values)

  if (variable_list.map(v => v.key).includes(key)) {
    // exists, update it
    logger(`Updating variable ${key}`)
    let uuid = variable_list.filter(v => v.key == key)[0].uuid
    await fetch(`${targetUrl}/${uuid}`,
      {
        method: 'PUT',
        body: JSON.stringify({
          key,
          value,
          secured: secure
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
        }
      })

  } else {
    // doesn't exist, create it
    logger(`Creating variable ${key}`)
    await fetch(`${targetUrl}`,
      {
        method: 'POST',
        body: JSON.stringify({
          key,
          value,
          secured: secure
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${base64.encode(`${user}:${password}`)}`
        }
      })
  }

  logger(`Variable ${key} set to ${value} in repository ${repository}`)
  return 0

}

module.exports = {
  runPipeline,
  setVariable
}