#!/usr/bin/env bash
# Post-deploy smoke test: the health endpoint plus one authenticated round trip.
#
# Usage:
#   BASE_URL=https://host:4455 SMOKE_EMAIL=… SMOKE_PASSWORD=… ./smoke-test.sh
# Set CURL_INSECURE=1 only against a throwaway local/dev endpoint (never staging/prod).
set -euo pipefail

: "${BASE_URL:?BASE_URL is required}"
: "${SMOKE_EMAIL:?SMOKE_EMAIL is required}"
: "${SMOKE_PASSWORD:?SMOKE_PASSWORD is required}"

curl_opts=(-fsS --max-time 15)
[ -n "${CURL_INSECURE:-}" ] && curl_opts+=(-k)

echo "==> Health"
curl "${curl_opts[@]}" "$BASE_URL/actuator/health" | grep -q '"status":"UP"'

echo "==> Authenticated round trip (login -> /users/me)"
login_body="$(printf '{"email":"%s","password":"%s"}' "$SMOKE_EMAIL" "$SMOKE_PASSWORD")"
token="$(curl "${curl_opts[@]}" -X POST "$BASE_URL/api/v1/auth/login" \
  -H 'Content-Type: application/json' -d "$login_body" \
  | sed -n 's/.*"accessToken":"\([^"]*\)".*/\1/p')"

if [ -z "$token" ]; then
  echo "ERROR: login did not return an access token" >&2
  exit 1
fi

curl "${curl_opts[@]}" "$BASE_URL/api/v1/users/me" \
  -H "Authorization: Bearer $token" | grep -q "$SMOKE_EMAIL"

echo "==> Smoke test passed"
