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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET_SCRIPT="$SCRIPT_DIR/s06-acceptance-data.sh"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

pass() {
  printf 'PASS: %s\n' "$1"
}

fail() {
  printf 'FAIL: %s\n' "$1" >&2
  exit 1
}

run_expect_fail() {
  local name="$1"
  local expected="$2"
  shift 2
  local out="$TMP_DIR/${name}.log"
  set +e
  "$@" >"$out" 2>&1
  local exit_code=$?
  set -e
  if [[ $exit_code -eq 0 ]]; then
    cat "$out" >&2
    fail "$name unexpectedly passed"
  fi
  if ! grep -Fq "$expected" "$out"; then
    cat "$out" >&2
    fail "$name did not mention expected text: $expected"
  fi
  pass "$name"
}

run_expect_pass() {
  local name="$1"
  shift
  local out="$TMP_DIR/${name}.log"
  "$@" >"$out" 2>&1 || {
    cat "$out" >&2
    fail "$name failed"
  }
  pass "$name"
}

run_expect_fail "missing-auth-token" "AUTH_TOKEN is required" env -u AUTH_TOKEN bash "$TARGET_SCRIPT"
run_expect_fail "bad-auth-token" "AUTH_TOKEN appears invalid or lacks access" env AUTH_TOKEN="not-a-real-token" bash "$TARGET_SCRIPT"

if [[ -n "${TEST_AUTH_TOKEN:-}" ]]; then
  run_expect_pass "happy-path-first-run" env AUTH_TOKEN="$TEST_AUTH_TOKEN" bash "$TARGET_SCRIPT"
  run_expect_pass "happy-path-second-run" env AUTH_TOKEN="$TEST_AUTH_TOKEN" bash "$TARGET_SCRIPT"
else
  printf 'SKIP: happy-path rerun requires TEST_AUTH_TOKEN.\n'
fi
