#!/usr/bin/env bash
# Read the latest stub-generated OTP code for ${TEST_PHONE} from the
# backend's dev-only /internal/_test/peek-otp endpoint.
#
# Echoes the 6-digit code to stdout. Maestro captures the last line of
# stdout into the variable named by the calling runScript step.
set -euo pipefail

phone="${TEST_PHONE:-}"
url="${BACKEND_INTERNAL_URL:-http://localhost:3001}"

if [[ -z "$phone" ]]; then
  echo "TEST_PHONE env var required" >&2
  exit 1
fi

# url-encode the leading +
encoded_phone="$(printf %s "$phone" | sed 's/+/%2B/')"
resp="$(curl -fsS "${url}/internal/_test/peek-otp?phone=${encoded_phone}")"
echo "$resp" | jq -r .code
