#!/usr/bin/env node
// Node loads this file and can't transpile it so we have to disable Flow
/* eslint-disable flowtype/require-valid-file-annotation */
const request = require('request-promise-native');

const PR_NUMBER_REGEX = new RegExp('([^/]*)$');
const USER_AGENT = 'StorybookBot/1.1.0';

const getEnvVar = varname => {
  const val = process.env[varname];
  if (undefined === val) {
    throw new Error(`Missing required environment variable: ${varname}`);
  }

  return val;
};

const REPO_NAME = getEnvVar('CIRCLE_PROJECT_REPONAME');
const GITHUB_USERNAME = getEnvVar('DEVTOOLS_GITHUB_USERNAME');
const GITHUB_API_TOKEN = getEnvVar('DEVTOOLS_GITHUB_API_TOKEN');
const BRANCH_NAME = getEnvVar('CIRCLE_BRANCH');
const COMMIT_SHA = getEnvVar('CIRCLE_SHA1');
const PULL_REQUEST_URL = process.env.CIRCLE_PULL_REQUEST;

const message = `
### Patchwork storybook has been deployed to static!

Branch Storybook: https://static.iad.w10e.com/docs/micro-apps/patchwork/${BRANCH_NAME}

Master Storybook: https://static.iad.w10e.com/docs/micro-apps/patchwork

#### Generated For: ${COMMIT_SHA}

> generator: ${USER_AGENT}
`;

const postComment = async () => {
  // Only comment on pull request
  if (PULL_REQUEST_URL != null) {
    const pullRequestNumber = PULL_REQUEST_URL.match(PR_NUMBER_REGEX)[0];

    const comments = await request({
      method: 'GET',
      uri: `https://api.github.com/repos/wealthsimple/${REPO_NAME}/issues/${pullRequestNumber}/comments`,
      headers: {
        'User-Agent': USER_AGENT,
        'Content-type': 'application/json',
      },
      json: true,
    }).auth(GITHUB_USERNAME, GITHUB_API_TOKEN, true);

    console.log(comments);

    let githubCommentId;
    const hasCommented = comments.some(comment => {
      if (
        // Storybook Bot has previously commented on PR
        comment.body.includes(USER_AGENT) &&
        comment.user.login === GITHUB_USERNAME
      ) {
        githubCommentId = comment.id;
        return true;
      }
      return false;
    });

    if (hasCommented && githubCommentId) {
      console.log('Already commented on PR');
      // Update comment with most recent Github SHA.
      await request({
        method: 'PATCH',
        uri: `https://api.github.com/repos/wealthsimple/${REPO_NAME}/issues/comments/${githubCommentId}`,
        body: {
          body: message,
        },
        headers: {
          'User-Agent': USER_AGENT,
          'Content-type': 'application/json',
        },
        json: true,
      }).auth(GITHUB_USERNAME, GITHUB_API_TOKEN, true);
    } else {
      console.log('Commenting on PR for first time');
      await request({
        method: 'POST',
        uri: `https://api.github.com/repos/wealthsimple/${REPO_NAME}/issues/${pullRequestNumber}/comments`,
        body: {
          body: message,
        },
        headers: {
          'User-Agent': USER_AGENT,
          'Content-type': 'application/json',
        },
        json: true,
      }).auth(GITHUB_USERNAME, GITHUB_API_TOKEN, true);
    }
  } else {
    // eslint-disable-next-line no-console
    console.log('No PR available');
  }
};

postComment();
