const fetch  = require( 'node-fetch').default
const { replaceInText, requireValue } = require( './services/utils')
const getVersion = require( './services/version')

module.exports = async (options, logger) => {

  const versionInfo = getVersion(options, logger)

  let {
    url = process.env.SLACK_WEBHOOK_URL || 'https://hooks.slack.com/services/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',
    text = requireValue('text'),
    channel = 'delivery-log',
    workspace = process.env.BITBUCKET_WORKSPACE || 'viewdo',
    repo = process.env.BITBUCKET_REPO_SLUG || 'dxp-platform',
    build_number = process.env.BITBUCKET_BUILD_NUMBER || '1'
  } = options

  logger(`Sending slack message to ${channel}: ${text}\n${url}`)

  await fetch(url, {
    method: 'POST',
    body: JSON.stringify( {
      channel,
      attachments: [
        {
          "fallback": text,
          "color": "#439FE0",
          "pretext": `Notification sent from <https://bitbucket.org/${workspace}/${repo}/addon/pipelines/home#!/results/${build_number}|Pipeline #${build_number}>`,
          "text": replaceInText(versionInfo, text),
          "mrkdwn_in": ["pretext"]
        }
      ]
    }),
    headers: {'Content-Type': 'application/json'}
  });
  logger(`Message sent`.green);
  return 0;

}
