// @flow

const { logger } = require('@lagoon/commons/src/local-logging');
const { sendToLagoonLogs } = require('@lagoon/commons/src/logs');
const { createDeployTask } = require('@lagoon/commons/src/tasks');

import type { WebhookRequestData, deployData, ChannelWrapper, Project  } from '../types';

async function bitbucketPush(webhook: WebhookRequestData, project: project) {

    const {
      webhooktype,
      event,
      giturl,
      uuid,
      body,
    } = webhook;

    const branchName = body.push.changes[0].new.name.toLowerCase()
    const sha = body.push.changes[0].commits[0].hash

    const meta = {
      branch: branchName,
      sha: sha
    }

    const data: deployData = {
      projectName: project.name,
      type: 'branch',
      branchName: branchName,
      sha: sha,
    }

    let logMessage = `\`<${body.push.changes[0].new.links.html.href}>\``
    if (sha) {
      const shortSha: string = sha.substring(0, 7)
      logMessage = `${logMessage} (<${body.push.changes[0].new.target.links.html.href}|${shortSha}>)`
    }

    try {
      const taskResult = await createDeployTask(data);
      sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handled`, meta,
        `*[${project.name}]* ${logMessage} pushed in <${body.repository.links.html.href}|${body.repository.full_name}>`
      )
      return;
    } catch (error) {
      switch (error.name) {
        case "ProjectNotFound":
        case "NoActiveSystemsDefined":
        case "UnknownActiveSystem":
        case "NoNeedToDeployBranch":
          // These are not real errors and also they will happen many times. We just log them locally but not throw an error
          sendToLagoonLogs('info', project.name, uuid, `${webhooktype}:${event}:handledButNoTask`, meta,
            `*[${project.name}]* ${logMessage}. No deploy task created, reason: ${error}`
          )
          return;

        default:
          // Other messages are real errors and should reschedule the message in RabbitMQ in order to try again
          throw error
      }
    }

}

module.exports = bitbucketPush;

@@ -593,16 +593,671 @@
 %5D.hash%0A%0A
+    // for each item in the body.commits array, search for our regular expression; this is an arroy of boolean%0A    // which is .reduced into a single true if any are true.%0A    const skip_deploy = body.commits.map( commit =%3E Array.isArray(commit.message.match(/%5C%5Bskip deploy%5C%5D%7C%5C%5Bdeploy skip%5C%5D/i)))%0A                                    .reduce( function(a,i,x,z) %7B return a%7C%7Ci %7D)%0A    if (skip_deploy) %7B%0A      sendToLagoonLogs('info', project.name, uuid, %60$%7Bwebhooktype%7D:$%7Bevent%7D:skipped%60, meta,%0A        %60*%5B$%7Bproject.name%7D%5D* $%7BlogMessage%7D pushed in %3C$%7Bbody.repository.html_url%7D%7C$%7Bbody.repository.full_name%7D%3E *deployment skipped*%60%0A      )%0A      return;%0A    %7D%0A%0A
     cons

add skip deploy code to bitbucket too.