#!/bin/bash

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_success() { echo -e "${GREEN}✅ $1${NC}"; }
print_error() { echo -e "${RED}❌ $1${NC}"; }
print_warning() { echo -e "${YELLOW}⚠️  $1${NC}"; }
print_info() { echo -e "${BLUE}ℹ️  $1${NC}"; }

echo "========================================="
echo "  Complete Amadeus Integration Test"
echo "========================================="
echo ""

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

# Test 2: Check Amadeus authentication
echo "Test 2: Checking Amadeus authentication..."
AUTH_LOG=$(docker-compose logs app 2>/dev/null | grep -i "amadeus" | grep -i "auth" | tail -3)
if echo "$AUTH_LOG" | grep -q "Successfully authenticated"; then
    print_success "Amadeus authentication successful"
    echo "$AUTH_LOG" | grep "Successfully authenticated"
elif echo "$AUTH_LOG" | grep -q "credentials not configured"; then
    print_error "Credentials not configured - using mock mode"
    echo "Run: ./configure-amadeus-credentials.sh"
    exit 1
else
    print_warning "Authentication status unclear"
    echo "Recent logs:"
    echo "$AUTH_LOG"
fi
echo ""

# Test 3: Get auth token
echo "Test 3: 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 token"
    exit 1
fi
echo ""

# Test 4: Test real flight search
echo "Test 4: Testing REAL Amadeus flight search..."
echo "   Searching: Madrid (MAD) → New York (NYC)"
echo "   Date: 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": 3
  }')

# Check response
if echo "$SEARCH_RESPONSE" | jq empty 2>/dev/null; then
    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 real offers from Amadeus"
        echo ""
        echo "Sample offer details:"
        echo "$SEARCH_RESPONSE" | jq '.data[0] | {
            id: .id,
            price: .price.total,
            currency: .price.currency,
            validatingAirlineCodes: .validatingAirlineCodes,
            numberOfBookableSeats: .numberOfBookableSeats,
            itineraries: .itineraries | length
        }' 2>/dev/null
        
        # Save offer ID for later
        OFFER_ID=$(echo "$SEARCH_RESPONSE" | jq -r '.data[0].id')
        OFFER_PRICE=$(echo "$SEARCH_RESPONSE" | jq -r '.data[0].price.total')
    else
        print_warning "No offers found (might be normal for test data)"
        echo "Response:"
        echo "$SEARCH_RESPONSE" | jq '.' 2>/dev/null
    fi
else
    print_error "Flight search failed"
    echo "Response: $SEARCH_RESPONSE"
    exit 1
fi
echo ""

# Test 5: Check circuit breaker
echo "Test 5: 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)"
else
    print_info "Circuit breaker state: $CB_STATE"
fi
echo ""

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

# Test 7: Verify real API usage
echo "Test 7: Verifying real Amadeus API usage..."
if docker-compose logs app 2>/dev/null | tail -50 | grep -q "mock"; then
    print_warning "Application might be using mock data"
    echo "Check logs: docker-compose logs app | grep -i mock"
else
    print_success "Using real Amadeus API (no mock data detected)"
fi
echo ""

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

if [ "$OFFER_COUNT" -gt 0 ]; then
    print_success "Amadeus Integration: WORKING ✅"
    echo ""
    echo "Your integration is fully functional!"
    echo ""
    echo "Sample flight found:"
    echo "  Route: MAD → NYC"
    echo "  Price: $OFFER_PRICE EUR"
    echo "  Offer ID: $OFFER_ID"
    echo ""
    echo "Next steps:"
    echo "  1. Try complete booking: ./first-booking-tutorial.sh"
    echo "  2. Explore API: http://localhost:8081/swagger-ui.html"
    echo "  3. View metrics: curl http://localhost:8081/actuator/metrics"
else
    print_warning "Integration configured but no offers found"
    echo ""
    echo "This might be normal. Possible reasons:"
    echo "  - No flights available for selected route/date"
    echo "  - Test API limitations"
    echo "  - Try different dates or routes"
fi

echo ""
echo "Useful commands:"
echo "  - View logs: docker-compose logs -f app"
echo "  - Check health: curl http://localhost:8081/actuator/health | jq"
echo "  - Test booking: ./first-booking-tutorial.sh"
echo ""
