#!/usr/bin/env bash
# Regression harness for #807: ranged GLPI list requests may return HTTP 206.
#
# Each shipped list wrapper must render a healthy 206 response and must retain
# its non-zero error behavior for a genuine HTTP failure.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/glpi-list-http-status}"
TOOL_DIR="$WORK_DIR/tools/glpi"
BIN_DIR="$WORK_DIR/bin"

rm -rf "$WORK_DIR"
mkdir -p "$TOOL_DIR" "$BIN_DIR" "$WORK_DIR/tools/_lib"
trap 'rm -rf "$WORK_DIR"' EXIT

for wrapper in ticket-list.sh computer-list.sh user-list.sh; do
  cp "$SCRIPT_DIR/$wrapper" "$TOOL_DIR/$wrapper"
done

cat > "$WORK_DIR/tools/_lib/credentials.sh" <<'SH'
load_credentials() {
  export GLPI_URL="https://glpi.test/apirest.php"
  export GLPI_APP_TOKEN="test-app-token"
}
SH

cat > "$TOOL_DIR/session-init.sh" <<'SH'
#!/usr/bin/env bash
printf '%s\n' 'test-session-token'
SH
chmod +x "$TOOL_DIR/session-init.sh"

cat > "$BIN_DIR/curl" <<'SH'
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '[{"id":42,"priority":3,"status":1,"name":"Regression fixture","date_mod":"2026-07-16 10:00:00","serial":"SER-42","states_id":1,"realname":"Fixture","firstname":"GLPI","is_active":1}]'
printf '%s\n' "${GLPI_TEST_HTTP_CODE:?GLPI_TEST_HTTP_CODE is required}"
SH
chmod +x "$BIN_DIR/curl"

export MOSAIC_HOME="$WORK_DIR"
export PATH="$BIN_DIR:$PATH"

wrappers=(ticket-list.sh computer-list.sh user-list.sh)
resources=(tickets computers users)
headings=(PRIORITY SERIAL USERNAME)
fail=0

for index in "${!wrappers[@]}"; do
  wrapper="${wrappers[$index]}"
  resource="${resources[$index]}"
  heading="${headings[$index]}"
  path="$TOOL_DIR/$wrapper"

  if ! output=$(GLPI_TEST_HTTP_CODE=206 bash "$path" 2>&1); then
    echo "FAIL: $wrapper rejected healthy HTTP 206" >&2
    fail=1
  elif [[ "$output" != *"$heading"* || "$output" != *"Regression fixture"* ]]; then
    echo "FAIL: $wrapper did not render the HTTP 206 list response" >&2
    fail=1
  else
    echo "PASS: $wrapper renders HTTP 206"
  fi

  rc=0
  output=$(GLPI_TEST_HTTP_CODE=401 bash "$path" 2>&1) || rc=$?
  if [[ "$rc" -eq 0 ]]; then
    echo "FAIL: $wrapper accepted HTTP 401" >&2
    fail=1
  elif [[ "$output" != *"Error: Failed to list $resource (HTTP 401)"* ]]; then
    echo "FAIL: $wrapper changed the HTTP failure diagnostic" >&2
    fail=1
  else
    echo "PASS: $wrapper rejects HTTP 401"
  fi
done

if [[ "$fail" -eq 0 ]]; then
  echo "ALL PASS: test-list-http-status.sh"
fi

exit "$fail"
