#!/usr/bin/env bash
set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# shellcheck disable=SC1090
source "${repo_dir}/templates/scripts/pr"

tmp_dir="$(mktemp -d)"
cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT

EDITED_ISSUES=()
COMMENTED_ISSUES=()
OPEN_ISSUES_JSON="[]"

gh() {
  if [[ "$1" == "issue" && "$2" == "list" ]]; then
    printf '%s\n' "$OPEN_ISSUES_JSON"
    return 0
  fi

  if [[ "$1" == "issue" && "$2" == "view" ]]; then
    printf 'CLOSED\n'
    return 0
  fi

  if [[ "$1" == "issue" && "$2" == "edit" ]]; then
    EDITED_ISSUES+=("$3")
    return 0
  fi

  if [[ "$1" == "issue" && "$2" == "comment" ]]; then
    COMMENTED_ISSUES+=("$3")
    return 0
  fi

  echo "unexpected gh invocation: $*" >&2
  return 1
}

issue_array_with_labels() {
  local labels="$1"

  jq -cn \
    --arg labels "$labels" \
    '[
      {
        number: 42,
        title: "Dependent issue",
        url: "https://github.com/acme/repo/issues/42",
        body: "## Blocked by\n\n- #10",
        labels: ($labels | split(",") | map(select(length > 0) | {name: .}))
      }
    ]'
}

run_promotion() {
  local output_file="$1"
  EDITED_ISSUES=()
  COMMENTED_ISSUES=()

  promote_unblocked_issues_after_merge 99 "https://github.com/acme/repo/pull/99" 10 >"$output_file"
}

assert_no_promotions() {
  if [[ "${#EDITED_ISSUES[@]}" -ne 0 ]]; then
    echo "expected no promoted issues, got: ${EDITED_ISSUES[*]}" >&2
    exit 1
  fi
}

assert_promoted_issue_42() {
  if [[ "${#EDITED_ISSUES[@]}" -ne 1 || "${EDITED_ISSUES[0]}" != "42" ]]; then
    echo "expected issue #42 to be promoted, got: ${EDITED_ISSUES[*]-}" >&2
    exit 1
  fi
}

OPEN_ISSUES_JSON="$(issue_array_with_labels "")"
run_promotion "${tmp_dir}/promoted.out"
assert_promoted_issue_42

if ! grep -q "Promoted issue #42 to ready-for-agent" "${tmp_dir}/promoted.out"; then
  echo "promotion message was not printed" >&2
  exit 1
fi

OPEN_ISSUES_JSON="$(issue_array_with_labels "ready-for-agent")"
run_promotion "${tmp_dir}/already-ready.out"
assert_no_promotions

if ! grep -q "already has ready-for-agent" "${tmp_dir}/already-ready.out"; then
  echo "already-ready message was not printed" >&2
  exit 1
fi

for label in needs-info needs-triage ready-for-human wontfix; do
  OPEN_ISSUES_JSON="$(issue_array_with_labels "$label")"
  run_promotion "${tmp_dir}/${label}.out"
  assert_no_promotions

  if ! grep -q "conflicting label ${label}" "${tmp_dir}/${label}.out"; then
    echo "conflicting label message was not printed for ${label}" >&2
    exit 1
  fi
done

echo "promote unblocked issues test passed"
