#!/bin/bash

echo "========================================="
echo "  Amadeus API Integration Test"
echo "========================================="
echo ""

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# Test 1: Check if application is running
echo "Test 1: Checking if application is running..."
if curl -s http://localhost:8081/actuator/health > /dev/null; then
    print_success "Application is running"
else
    print_error "Application is not running. Start it with: docker-compose up -d"
    exit 1
fi
echo ""

# Test 2: Check Amadeus API health
echo "Test 2: Checking Amadeus API health..."
AMADEUS_HEALTH=$(curl -s http://localhost:8081/actuator/health | jq -r '.components.amadeusApi.status' 2>/dev/null)
if [ "$AMADEUS_HEALTH" = "UP" ]; then
    print_success "Amadeus API health check passed"
else
    print_warning "Amadeus API health status: $AMADEUS_HEALTH"
fi
echo ""

# Test 3: Check authentication logs
echo "Test 3: Checking Amadeus authentication..."
AUTH_LOG=$(docker-compose logs app 2>/dev/null | grep -i "amadeus" | grep -i "auth" | tail -1)
if echo "$AUTH_LOG" | grep -q "Successfully authenticated"; then
    print_success "Amadeus authentication successful"
    echo "   $AUTH_LOG"
elif echo "$AUTH_LOG" | grep -q "credentials not configured"; then
    print_warning "Using mock mode (credentials not configured)"
    echo "   Configure credentials in .env file to use real Amadeus API"
else
    print_warning "Authentication status unclear"
    echo "   Last auth log: $AUTH_LOG"
fi
echo ""

# Test 4: Get authentication token
echo "Test 4: Getting authentication token..."
TOKEN=$(curl -s -X POST "http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=superadmin" \
  -d "password=admin123" \
  -d "grant_type=password" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" 2>/dev/null | jq -r '.access_token')

if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ]; then
    print_success "Authentication token obtained"
else
    print_error "Failed to get authentication token"
    echo "   Make sure Keycloak is running and configured"
    exit 1
fi
echo ""

# Test 5: Test flight search API
echo "Test 5: Testing flight search API..."
echo "   Searching flights: MAD -> NYC on 2026-03-15"
echo ""

SEARCH_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/flights/search" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "originLocationCode": "MAD",
    "destinationLocationCode": "NYC",
    "departureDate": "2026-03-15",
    "adults": 1,
    "travelClass": "ECONOMY",
    "currencyCode": "EUR",
    "max": 5
  }')

# Check if response is valid JSON
if echo "$SEARCH_RESPONSE" | jq empty 2>/dev/null; then
    # Check if we got flight offers
    OFFER_COUNT=$(echo "$SEARCH_RESPONSE" | jq '.data | length' 2>/dev/null)
    
    if [ "$OFFER_COUNT" -gt 0 ]; then
        print_success "Flight search successful! Found $OFFER_COUNT offers"
        echo ""
        echo "Sample offer:"
        echo "$SEARCH_RESPONSE" | jq '.data[0] | {
            id: .id,
            price: .price.total,
            currency: .price.currency,
            validatingAirlineCodes: .validatingAirlineCodes,
            numberOfBookableSeats: .numberOfBookableSeats
        }' 2>/dev/null
    else
        print_warning "Flight search returned 0 offers"
        echo "   This might be normal if using mock data or no flights available"
    fi
else
    print_error "Flight search failed"
    echo "   Response: $SEARCH_RESPONSE"
fi
echo ""

# Test 6: Check circuit breaker status
echo "Test 6: Checking circuit breaker status..."
CB_STATE=$(curl -s http://localhost:8081/actuator/health | jq -r '.components.circuitBreakers.details.amadeus.state' 2>/dev/null)
if [ "$CB_STATE" = "CLOSED" ]; then
    print_success "Circuit breaker is CLOSED (healthy)"
elif [ "$CB_STATE" = "OPEN" ]; then
    print_error "Circuit breaker is OPEN (too many failures)"
    echo "   Wait 10 seconds for automatic recovery or check logs for errors"
elif [ "$CB_STATE" = "HALF_OPEN" ]; then
    print_warning "Circuit breaker is HALF_OPEN (testing recovery)"
else
    print_warning "Circuit breaker state: $CB_STATE"
fi
echo ""

# Test 7: Check recent logs for errors
echo "Test 7: Checking for recent errors..."
ERROR_COUNT=$(docker-compose logs app 2>/dev/null | grep -i "error" | grep -i "amadeus" | wc -l | tr -d ' ')
if [ "$ERROR_COUNT" -eq 0 ]; then
    print_success "No Amadeus-related errors in logs"
else
    print_warning "Found $ERROR_COUNT Amadeus-related errors in logs"
    echo "   Run 'docker-compose logs app | grep -i amadeus | grep -i error' to see details"
fi
echo ""

# Summary
echo "========================================="
echo "  Test Summary"
echo "========================================="
echo ""

# Check if using real API or mock
if docker-compose logs app 2>/dev/null | grep -q "credentials not configured"; then
    echo "📝 Status: Using MOCK mode"
    echo ""
    echo "To use real Amadeus API:"
    echo "  1. Get credentials from https://developers.amadeus.com/"
    echo "  2. Run: ./setup-amadeus.sh"
    echo "  3. Or manually edit .env file with your credentials"
    echo ""
else
    echo "📝 Status: Using REAL Amadeus API"
    echo ""
fi

echo "📖 For more information:"
echo "   - Read: docs/AMADEUS_INTEGRATION_GUIDE.md"
echo "   - View logs: docker-compose logs app | grep -i amadeus"
echo "   - API docs: http://localhost:8081/swagger-ui.html"
echo ""
