#!/bin/bash
# Manual test script for authentication endpoints

BASE_URL="http://127.0.0.1:8000"

echo "=== Testing Normogen Authentication ==="
echo ""

# Test 1: Health check
echo "1. Testing health check..."
curl -s "$BASE_URL/health" | jq .
echo ""

# Test 2: Ready check
echo "2. Testing ready check..."
curl -s "$BASE_URL/ready" | jq .
echo ""

# Test 3: Register a new user
echo "3. Registering a new user..."
EMAIL="test_$(uuidgen | cut -d'-' -f1)@example.com"
REGISTER_RESPONSE=$(curl -s -X POST "$BASE_URL/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{"email":"'"$EMAIL"'","password_hash":"hashed_password_placeholder","encrypted_recovery_phrase":"encrypted_phrase_placeholder","recovery_phrase_iv":"iv_placeholder","recovery_phrase_auth_tag":"auth_tag_placeholder"}')

echo "$REGISTER_RESPONSE" | jq .
echo ""

# Extract user_id for later use
USER_ID=$(echo "$REGISTER_RESPONSE" | jq -r '.user_id')
echo "Created user ID: $USER_ID"
echo ""

# Test 4: Login
echo "4. Logging in..."
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"email":"'"$EMAIL"'","password_hash":"hashed_password_placeholder"}')

echo "$LOGIN_RESPONSE" | jq .
echo ""

# Extract tokens
ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.access_token')
REFRESH_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.refresh_token')

echo "Access Token: ${ACCESS_TOKEN:0:50}..."
echo "Refresh Token: ${REFRESH_TOKEN:0:50}..."
echo ""

# Test 5: Get profile without auth (should fail)
echo "5. Testing profile endpoint WITHOUT auth (should return 401)..."
curl -s "$BASE_URL/api/users/me" -i | head -n 1
echo ""

# Test 6: Get profile with auth (should succeed)
echo "6. Testing profile endpoint WITH auth (should return 200)..."
PROFILE_RESPONSE=$(curl -s "$BASE_URL/api/users/me" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

echo "$PROFILE_RESPONSE" | jq .
echo ""

# Test 7: Refresh token
echo "7. Testing refresh token..."
REFRESH_RESPONSE=$(curl -s -X POST "$BASE_URL/api/auth/refresh" \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"'"$REFRESH_TOKEN"'}')

echo "$REFRESH_RESPONSE" | jq .
echo ""

# Test 8: Logout
echo "8. Testing logout..."
LOGOUT_RESPONSE=$(curl -s -X POST "$BASE_URL/api/auth/logout" \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"'"$REFRESH_TOKEN"'}')

echo "$LOGOUT_RESPONSE" | jq .
echo ""

echo "=== Tests Complete ==="
