#!/bin/bash

# Complete Amadeus Booking Flow Test
# This script tests: Authentication → Flight Search → Booking → Ticketing

set -e  # Exit on error

echo "=========================================="
echo "Amadeus Complete Booking Flow Test"
echo "=========================================="
echo ""

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

# Read credentials from .env file
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | grep 'AMADEUS_API' | xargs)
else
    echo -e "${RED}❌ Error: .env file not found${NC}"
    exit 1
fi

echo "Using credentials:"
echo "  API Key: $AMADEUS_API_KEY"
echo "  API Secret: ${AMADEUS_API_SECRET:0:5}***"
echo "  Base URL: $AMADEUS_API_BASE_URL"
echo ""

# Step 1: Get Access Token
echo "=========================================="
echo "Step 1: Getting Access Token"
echo "=========================================="

TOKEN_RESPONSE=$(curl -s -X POST \
  "$AMADEUS_API_BASE_URL/v1/security/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=$AMADEUS_API_KEY&client_secret=$AMADEUS_API_SECRET")

# Check if authentication was successful
if echo "$TOKEN_RESPONSE" | grep -q "error"; then
    echo -e "${RED}❌ Authentication Failed!${NC}"
    echo "$TOKEN_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$TOKEN_RESPONSE"
    echo ""
    echo "Please update your credentials in the .env file"
    echo "Get valid credentials from: https://developers.amadeus.com/my-apps"
    exit 1
fi

ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null)

if [ -z "$ACCESS_TOKEN" ]; then
    echo -e "${RED}❌ Failed to extract access token${NC}"
    echo "$TOKEN_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✅ Access Token obtained successfully${NC}"
echo "Token: ${ACCESS_TOKEN:0:20}..."
echo ""

# Step 2: Test Flight Inspiration Search (Simple test)
echo "=========================================="
echo "Step 2: Testing Flight Inspiration Search"
echo "=========================================="
echo "Searching for destinations from Paris (PAR) under 200 EUR..."
echo ""

INSPIRATION_RESPONSE=$(curl -s -X GET \
  "$AMADEUS_API_BASE_URL/v1/shopping/flight-destinations?origin=PAR&maxPrice=200" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

if echo "$INSPIRATION_RESPONSE" | grep -q "error"; then
    echo -e "${YELLOW}⚠️  Flight Inspiration Search returned an error${NC}"
    echo "$INSPIRATION_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$INSPIRATION_RESPONSE"
else
    echo -e "${GREEN}✅ Flight Inspiration Search successful${NC}"
    echo "$INSPIRATION_RESPONSE" | python3 -m json.tool 2>/dev/null | head -50
fi
echo ""

# Step 3: Search for Flights
echo "=========================================="
echo "Step 3: Searching for Flights"
echo "=========================================="
echo "Searching: Madrid (MAD) → New York (JFK)"
echo "Date: 2026-03-15"
echo "Passengers: 1 Adult"
echo ""

SEARCH_RESPONSE=$(curl -s -X GET \
  "$AMADEUS_API_BASE_URL/v2/shopping/flight-offers?originLocationCode=MAD&destinationLocationCode=JFK&departureDate=2026-03-15&adults=1&max=5" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

if echo "$SEARCH_RESPONSE" | grep -q "error"; then
    echo -e "${RED}❌ Flight Search Failed!${NC}"
    echo "$SEARCH_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$SEARCH_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✅ Flight Search successful${NC}"

# Extract first flight offer
FLIGHT_OFFER=$(echo "$SEARCH_RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if 'data' in data and len(data['data']) > 0:
    offer = data['data'][0]
    print(json.dumps(offer, indent=2))
    print('---PRICE---', file=sys.stderr)
    print(offer['price']['total'], file=sys.stderr)
else:
    print('No flights found', file=sys.stderr)
    sys.exit(1)
" 2>&1)

PRICE=$(echo "$FLIGHT_OFFER" | grep "---PRICE---" -A 1 | tail -1)
FLIGHT_OFFER=$(echo "$FLIGHT_OFFER" | grep -v "---PRICE---")

if [ -z "$FLIGHT_OFFER" ] || [ "$FLIGHT_OFFER" = "No flights found" ]; then
    echo -e "${RED}❌ No flights found${NC}"
    exit 1
fi

echo "Found flight offer:"
echo "  Price: $PRICE EUR"
echo ""

# Step 4: Price Flight Offer (Confirm pricing)
echo "=========================================="
echo "Step 4: Confirming Flight Price"
echo "=========================================="

PRICE_REQUEST=$(cat <<EOF
{
  "data": {
    "type": "flight-offers-pricing",
    "flightOffers": [
      $FLIGHT_OFFER
    ]
  }
}
EOF
)

PRICE_RESPONSE=$(curl -s -X POST \
  "$AMADEUS_API_BASE_URL/v1/shopping/flight-offers/pricing" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$PRICE_REQUEST")

if echo "$PRICE_RESPONSE" | grep -q "error"; then
    echo -e "${YELLOW}⚠️  Price confirmation returned an error${NC}"
    echo "$PRICE_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$PRICE_RESPONSE"
    echo ""
    echo "Continuing with original offer..."
    CONFIRMED_OFFER="$FLIGHT_OFFER"
else
    echo -e "${GREEN}✅ Price confirmed${NC}"
    CONFIRMED_OFFER=$(echo "$PRICE_RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if 'data' in data and 'flightOffers' in data['data'] and len(data['data']['flightOffers']) > 0:
    print(json.dumps(data['data']['flightOffers'][0], indent=2))
else:
    print('$FLIGHT_OFFER')
" 2>/dev/null)
fi
echo ""

# Step 5: Create Booking
echo "=========================================="
echo "Step 5: Creating Booking"
echo "=========================================="
echo "Creating booking with test passenger data..."
echo ""

BOOKING_REQUEST=$(cat <<EOF
{
  "data": {
    "type": "flight-order",
    "flightOffers": [
      $CONFIRMED_OFFER
    ],
    "travelers": [
      {
        "id": "1",
        "dateOfBirth": "1990-01-01",
        "name": {
          "firstName": "JOHN",
          "lastName": "DOE"
        },
        "gender": "MALE",
        "contact": {
          "emailAddress": "john.doe@example.com",
          "phones": [
            {
              "deviceType": "MOBILE",
              "countryCallingCode": "34",
              "number": "600000000"
            }
          ]
        },
        "documents": [
          {
            "documentType": "PASSPORT",
            "birthPlace": "Madrid",
            "issuanceLocation": "Madrid",
            "issuanceDate": "2015-04-14",
            "number": "00000000",
            "expiryDate": "2025-04-14",
            "issuanceCountry": "ES",
            "validityCountry": "ES",
            "nationality": "ES",
            "holder": true
          }
        ]
      }
    ]
  }
}
EOF
)

BOOKING_RESPONSE=$(curl -s -X POST \
  "$AMADEUS_API_BASE_URL/v1/booking/flight-orders" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d "$BOOKING_REQUEST")

if echo "$BOOKING_RESPONSE" | grep -q "error"; then
    echo -e "${RED}❌ Booking Creation Failed!${NC}"
    echo "$BOOKING_RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$BOOKING_RESPONSE"
    echo ""
    echo "This is expected in test environment - real bookings require:"
    echo "  - Valid passenger data"
    echo "  - Payment information"
    echo "  - Production API credentials"
    exit 0
fi

echo -e "${GREEN}✅ Booking Created Successfully!${NC}"

# Extract booking ID
BOOKING_ID=$(echo "$BOOKING_RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if 'data' in data and 'id' in data['data']:
    print(data['data']['id'])
" 2>/dev/null)

echo "Booking ID: $BOOKING_ID"
echo ""
echo "Booking Details:"
echo "$BOOKING_RESPONSE" | python3 -m json.tool 2>/dev/null | head -100

echo ""
echo "=========================================="
echo "Test Summary"
echo "=========================================="
echo -e "${GREEN}✅ Authentication: Success${NC}"
echo -e "${GREEN}✅ Flight Search: Success${NC}"
echo -e "${GREEN}✅ Price Confirmation: Success${NC}"
if [ -n "$BOOKING_ID" ]; then
    echo -e "${GREEN}✅ Booking Creation: Success${NC}"
    echo ""
    echo "Booking ID: $BOOKING_ID"
else
    echo -e "${YELLOW}⚠️  Booking Creation: Not completed (expected in test environment)${NC}"
fi
echo ""
echo "=========================================="
echo ""
echo "Note: In the test environment, actual bookings may not be created."
echo "For real bookings, you need:"
echo "  1. Production API credentials"
echo "  2. Valid payment information"
echo "  3. Real passenger data"
echo ""
