import R from "ramda"
import {tryCatchAsync} from "../utils/common"
import {getInitialCommitHash} from "../utils/branches"

import Api from "@octokit/rest"

const api = new Api()

export let isAuthenticated = false

export const authenticate = R.pipe(R.bind(api.authenticate, api), () => {
  isAuthenticated = true
})

export const createPullRequestOnProd = (name) =>
  R.pipeP(
    tryCatchAsync(
      () =>
        api.gitdata.createReference({
          owner: `webliumteam`,
          repo: `blocks`,
          ref: R.pipe(
            R.split(`/`),
            R.slice(0, 3),
            R.concat([`refs`, `heads`]),
            R.flip(R.concat)([`prod`]),
            R.join(`/`),
          )(name),
          sha: getInitialCommitHash(),
        }),
      console.log,
    ),
    tryCatchAsync(
      () =>
        api.pullRequests.create({
          owner: `webliumteam`,
          repo: `blocks`,
          head: name,
          base: R.pipe(R.split(`/`), R.slice(0, 3), R.flip(R.concat)([`prod`]), R.join(`/`))(name),
          title: `${name}: merge with prod`,
        }),
      console.log,
    ),
  )()
