const bbUrlPrefix = 'https://git.add123.com/rest/api/latest'

const pullRequestHasErrored = async pr => {
  const latestCommitId = pr?.fromRef?.latestCommit
  if (!latestCommitId) {
    return false
  }
  const buildStats = await fetch(`https://git.add123.com/rest/build-status/latest/commits/stats/${latestCommitId}`).then(resp => resp.json())
  return buildStats.failed !== 0
}

const getAllRepos = async () => {
  const allProjects = (await fetch(`${bbUrlPrefix}/projects`).then(resp => resp.json())).values
  const allProjectKeys = allProjects.map(project => project.key)
  let allRepos = await Promise.all(allProjectKeys.map(async key =>
    await fetch(`${bbUrlPrefix}/projects/${key}/repos?limit=999`)
      .then(resp => resp.json()).then(({ values }) => values)))
  allRepos = allRepos.flatMap(a => a)
  return allRepos
}

const getErroredPrs = async () => {
  const allPullRequests = (await getAllRepos()
    .then(async allRepos => {
      const prListUrls = allRepos.map(repo => `${bbUrlPrefix}/projects/ADD/repos/${repo.slug}/pull-requests`)
      return (await Promise.all(
          prListUrls.map(async prListUrl => await fetch(prListUrl).then(resp => resp.json())))
      ).flatMap(({values}) => values)
    }).catch(console.error)).filter(Boolean)
  const erroredPullRequests = []
  for (const pullRequest of allPullRequests) {
    if (await pullRequestHasErrored(pullRequest)) {
      erroredPullRequests.push(pullRequest)
    }
  }
  return erroredPullRequests
}

const getElementAfterErrorList = mainPanel => {
  for (const child of mainPanel.children) {
    if (child.innerHTML.includes('Recently closed pull requests')) {
      return child
    }
  }
  return mainPanel.children[1]
}

const showErroredPrs = async () => {
  if (getCurrentUser() !== 'sagevaillancourt') {
    return
  }
  const mainPanel = document.getElementsByClassName('main-panel')[0]
  let errorParent = document.getElementById('bb-addon-pr-error-table')
  let errorList = document.getElementById('bb-addon-pr-error-list')
  if (!errorParent) {
    errorParent = mainPanel.getElementsByClassName('dashboard-pull-request-table')[0].cloneNode()
    errorParent.id = 'bb-addon-pr-error-table'

    const header = document.createElement('h3')
    header.innerText = 'Pull requests with errors'
    errorParent.appendChild(header)

    errorList = document.createElement('ul')
    errorList.id = 'bb-addon-pr-error-list'
    errorList.style.listStyle = 'none'
    errorList.style.fontSize = '0.9em'
    errorParent.appendChild(errorList)

    mainPanel.insertBefore(errorParent, getElementAfterErrorList(mainPanel))
  }

  const erroredPrs = await getErroredPrs()
  Array.from(errorList.children).forEach(child => errorList.removeChild(child))
  erroredPrs.forEach(pr => {
    const element = document.createElement('li')
    const link = document.createElement('a')
    link.href = pr.links.self[0].href
    link.innerText = pr.title
    link.style.color = 'black'
    element.appendChild(link)
    errorList.appendChild(element)
  })
}

if (location.toString().includes('/dashboard')) {
  addFix(() => showErroredPrs().catch(console.error))
  setInterval(() => showErroredPrs().catch(console.error), 1000 * 60 * 2)
}