#!/bin/bash
# test-api.sh - Test Normogen API endpoints

BASE_URL="http://10.0.10.30:6800"

echo "================================"
echo "Testing Normogen API"
echo "Base URL: $BASE_URL"
echo "================================"
echo ""

# Test 1: Health check
echo "1. Health Check:"
curl -s -w "\nHTTP Status: %{http_code}\n" $BASE_URL/health || echo "FAILED: Connection refused"
echo ""

# Test 2: Ready check
echo "2. Ready Check:"
curl -s -w "\nHTTP Status: %{http_code}\n" $BASE_URL/ready || echo "FAILED: Connection refused"
echo ""

# Test 3: Register user
echo "3. Register User:"
REGISTER_RESPONSE=$(curl -s -X POST $BASE_URL/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "SecurePassword123!", "username": "testuser"}' \
  -w "\nHTTP Status: %{http_code}\n")
echo "$REGISTER_RESPONSE"
echo ""

# Test 4: Login
echo "4. Login:"
LOGIN_RESPONSE=$(curl -s -X POST $BASE_URL/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "SecurePassword123!"}' \
  -w "\nHTTP Status: %{http_code}\n")
echo "$LOGIN_RESPONSE"

# Extract token
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"access_token":"[^"]*"' | cut -d'"' -f4)
echo ""
echo "Extracted Token: ${TOKEN:0:20}..."
echo ""

# Test 5: Get user profile (only if we got a token)
if [ -n "$TOKEN" ]; then
  echo "5. Get User Profile:"
  curl -s $BASE_URL/api/users/me \
    -H "Authorization: Bearer $TOKEN" \
    -w "\nHTTP Status: %{http_code}\n"
  echo ""
  
  # Test 6: Logout
  echo "6. Logout:"
  curl -s -X POST $BASE_URL/api/auth/logout \
    -H "Authorization: Bearer $TOKEN" \
    -w "\nHTTP Status: %{http_code}\n"
  echo ""
else
  echo "5. Get User Profile: SKIPPED (No token)"
  echo ""
fi

echo "================================"
echo "Tests Complete"
echo "================================"
