#!/usr/bin/env bash
# Run k6 load tests for Darkwatch authentication endpoints
# Usage: ./run.sh [scenario]
#   scenario: mixed (default), login, logout, refresh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Load environment variables from .env if present
if [[ -f .env ]]; then
  set -a
  source .env
  set +a
fi

SCENARIO="${1:-mixed}"
OUTPUT_DIR="${SCRIPT_DIR}/results"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"

mkdir -p "$OUTPUT_DIR"

echo "=== Darkwatch Auth Load Test ==="
echo "Scenario: $SCENARIO"
echo "Target RPS: ${TARGET_RPS:-500}"
echo "Duration: ${DURATION:-300s}"
echo "Base URL: ${DARKWATCH_BASE_URL:-http://localhost:3000}"
echo ""

EXIT_CODE=0
case "$SCENARIO" in
  mixed)
    k6 run darkwatch-auth.js \
      --summary-export "$OUTPUT_DIR/summary-${TIMESTAMP}.json" \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json" || EXIT_CODE=$?
    ;;
  login)
    k6 run --scenario login_only darkwatch-auth.js \
      --summary-export "$OUTPUT_DIR/summary-${TIMESTAMP}.json" \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json" || EXIT_CODE=$?
    ;;
  logout)
    k6 run --scenario logout_only darkwatch-auth.js \
      --summary-export "$OUTPUT_DIR/summary-${TIMESTAMP}.json" \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json" || EXIT_CODE=$?
    ;;
  refresh)
    k6 run --scenario refresh_only darkwatch-auth.js \
      --summary-export "$OUTPUT_DIR/summary-${TIMESTAMP}.json" \
      --out json="$OUTPUT_DIR/results-${TIMESTAMP}.json" || EXIT_CODE=$?
    ;;
  *)
    echo "Unknown scenario: $SCENARIO"
    echo "Available: mixed, login, logout, refresh"
    exit 1
    ;;
esac

if [[ $EXIT_CODE -eq 0 ]]; then
  echo ""
  echo "✅ All thresholds passed!"
  echo "Results saved to: $OUTPUT_DIR/results-${TIMESTAMP}.json"
else
  echo ""
  echo "❌ Thresholds failed. Check output above."
  echo "Results saved to: $OUTPUT_DIR/results-${TIMESTAMP}.json"
fi

exit $EXIT_CODE
