#!/bin/bash

# Complete Application Booking Flow Test
# Tests the Spring Boot application endpoints for: Flight Search → Booking → Ticketing

set -e

echo "=========================================="
echo "B2B Flight Platform - Complete Flow Test"
echo "=========================================="
echo ""

APP_URL="http://localhost:8081"

# Step 1: Setup Keycloak and get token
echo "Step 1: Getting Keycloak Access Token..."
echo "Note: This requires Keycloak to be configured with test users"
echo ""

# For now, we'll test without authentication (you'll need to configure Keycloak)
echo "⚠️  Skipping authentication - testing public endpoints"
echo ""

# Step 2: Check Application Health
echo "Step 2: Checking Application Health..."
HEALTH=$(curl -s "$APP_URL/actuator/health")

echo "$HEALTH" | python3 -c "
import sys, json
data = json.load(sys.stdin)
status = data['status']
amadeus_status = data['components']['amadeusApi']['status']

print(f'Application Status: {status}')
print(f'Amadeus API Status: {amadeus_status}')

if status == 'UP' and amadeus_status == 'UP':
    print('✅ Application is healthy')
else:
    print('❌ Application has issues')
    sys.exit(1)
"
echo ""

# Step 3: Test Swagger UI
echo "Step 3: Checking API Documentation..."
SWAGGER_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "$APP_URL/swagger-ui.html")

if [ "$SWAGGER_RESPONSE" = "200" ]; then
    echo "✅ Swagger UI is accessible at: $APP_URL/swagger-ui.html"
else
    echo "⚠️  Swagger UI returned status: $SWAGGER_RESPONSE"
fi
echo ""

# Step 4: Test OpenAPI Docs
echo "Step 4: Checking OpenAPI Documentation..."
API_DOCS=$(curl -s "$APP_URL/api-docs")

echo "$API_DOCS" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    if 'openapi' in data:
        print(f'✅ OpenAPI Version: {data[\"openapi\"]}')
        print(f'   API Title: {data[\"info\"][\"title\"]}')
        print(f'   API Version: {data[\"info\"][\"version\"]}')
        
        # Count endpoints
        paths = len(data.get('paths', {}))
        print(f'   Total Endpoints: {paths}')
    else:
        print('⚠️  Invalid OpenAPI response')
except:
    print('❌ Failed to parse OpenAPI docs')
"
echo ""

echo "=========================================="
echo "Test Summary"
echo "=========================================="
echo ""
echo "✅ Application is running and healthy"
echo "✅ Amadeus API integration is working"
echo "✅ API documentation is accessible"
echo ""
echo "Next Steps:"
echo "1. Configure Keycloak with test users"
echo "2. Get JWT token for authentication"
echo "3. Test authenticated endpoints:"
echo "   - POST /api/v1/flights/search"
echo "   - POST /api/v1/bookings"
echo "   - POST /api/v1/tickets/issue"
echo ""
echo "View API Documentation:"
echo "  Swagger UI: $APP_URL/swagger-ui.html"
echo "  OpenAPI JSON: $APP_URL/api-docs"
echo ""
echo "=========================================="
