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

BASE_URL="${BASE_URL:-http://localhost}"
EMAIL="${EMAIL:-test@example.com}"
PASSWORD="${PASSWORD:--secret123}"

for cmd in curl jq hey; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "Missing required command: $cmd" >&2
    exit 1
  fi
done

LOGIN_PAYLOAD="$(jq -n \
  --arg email "$EMAIL" \
  --arg password "$PASSWORD" \
  '{email: $email, password: $password}')"

login() {
  curl -fsS -X POST "$BASE_URL/api/auth/login" \
    -H "Content-Type: application/json" \
    -d "$LOGIN_PAYLOAD" |
    jq -er '.accessToken'
}

if ! TOKEN="$(login)"; then
  echo "Login failed. Trying to register $EMAIL, then logging in again..." >&2
  curl -fsS -X POST "$BASE_URL/api/auth/register" \
    -H "Content-Type: application/json" \
    -d "$LOGIN_PAYLOAD" \
    >/dev/null
  TOKEN="$(login)"
fi

echo "Authenticated as $EMAIL"

for concurrency in 10 50 100 200; do
  echo "Load Level"
  hey -n 1000 -c "$concurrency" \
    -H "Authorization: Bearer $TOKEN" \
    "$BASE_URL/api/expenses"
done

echo "30s test"
hey -z 30s -c 50 \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/expenses"

echo "Test POST endpoint"
hey -n 500 -c 25 \
  -m POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Test expense","amount":12.50}' \
  http://localhost/api/expenses