#!/bin/bash

echo "========================================="
echo "  Amadeus First Booking Tutorial"
echo "========================================="
echo ""
echo "This script will walk you through creating"
echo "your first flight booking step by step."
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 1: Get Token
echo "Step 1: 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" | jq -r '.access_token')

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
    echo "❌ Failed to get authentication token"
    echo "   Make sure Keycloak is running and configured"
    exit 1
fi

echo "✅ Token obtained"
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 2: Search Flights
echo "Step 2: Searching for flights (MAD -> NYC)..."
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",
    "returnDate": "2026-03-22",
    "adults": 1,
    "travelClass": "ECONOMY",
    "currencyCode": "EUR",
    "max": 5
  }')

OFFER_ID=$(echo "$SEARCH_RESPONSE" | jq -r '.data[0].id')
OFFER_PRICE=$(echo "$SEARCH_RESPONSE" | jq -r '.data[0].price.total')

if [ -z "$OFFER_ID" ] || [ "$OFFER_ID" = "null" ]; then
    echo "❌ Failed to search flights"
    echo "   Response: $SEARCH_RESPONSE"
    exit 1
fi

echo "✅ Found flights!"
echo "   Selected offer: $OFFER_ID"
echo "   Price: $OFFER_PRICE EUR"
echo ""
echo "First offer details:"
echo "$SEARCH_RESPONSE" | jq '.data[0] | {
    id: .id,
    price: .price.total,
    currency: .price.currency,
    validatingAirlineCodes: .validatingAirlineCodes
}'
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 3: Create Agency
echo "Step 3: Creating test agency..."
AGENCY_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/agencies" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"name\": \"Test Travel Agency $(date +%s)\",
    \"matriculeNumber\": \"TEST$(date +%s)\",
    \"contactEmail\": \"agency@test.com\",
    \"contactPhone\": \"+34612345678\",
    \"subscriptionType\": \"MONTHLY\",
    \"markupPercentage\": 5.0
  }")

AGENCY_ID=$(echo "$AGENCY_RESPONSE" | jq -r '.id')

if [ -z "$AGENCY_ID" ] || [ "$AGENCY_ID" = "null" ]; then
    echo "❌ Failed to create agency"
    echo "   Response: $AGENCY_RESPONSE"
    exit 1
fi

echo "✅ Agency created: $AGENCY_ID"
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 4: Verify Agency
echo "Step 4: Verifying agency..."
VERIFY_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/agencies/$AGENCY_ID/verify" \
  -H "Authorization: Bearer $TOKEN")

echo "✅ Agency verified"
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 5: Create Booking
echo "Step 5: Creating booking with passenger details..."
BOOKING_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/bookings" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"agencyId\": \"$AGENCY_ID\",
    \"flightOfferId\": \"$OFFER_ID\",
    \"passengers\": [{
      \"firstName\": \"JOHN\",
      \"lastName\": \"DOE\",
      \"dateOfBirth\": \"1990-01-15\",
      \"gender\": \"MALE\",
      \"email\": \"john.doe@example.com\",
      \"phone\": \"+34612345678\",
      \"passportNumber\": \"A12345678\",
      \"passportExpiry\": \"2030-12-31\",
      \"passportCountry\": \"ES\",
      \"nationality\": \"ES\"
    }],
    \"contactEmail\": \"booking@test.com\",
    \"contactPhone\": \"+34612345678\"
  }")

BOOKING_ID=$(echo "$BOOKING_RESPONSE" | jq -r '.id')

if [ -z "$BOOKING_ID" ] || [ "$BOOKING_ID" = "null" ]; then
    echo "❌ Failed to create booking"
    echo "   Response: $BOOKING_RESPONSE"
    exit 1
fi

echo "✅ Booking created: $BOOKING_ID"
echo ""
echo "Booking details:"
echo "$BOOKING_RESPONSE" | jq '{
    id: .id,
    pnr: .pnr,
    status: .status,
    totalPrice: .totalPrice
}'
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 6: Add Wallet Funds
echo "Step 6: Adding funds to agency wallet..."
RECHARGE_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/wallet/recharge" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"agencyId\": \"$AGENCY_ID\",
    \"amount\": 2000.00,
    \"currency\": \"EUR\",
    \"paymentMethod\": \"BANK_TRANSFER\",
    \"reference\": \"TEST-RECHARGE-$(date +%s)\"
  }")

echo "✅ Recharge request created"
echo ""

echo "Approving recharge..."
RECHARGE_ID=$(curl -s -X GET "http://localhost:8081/api/v1/wallet/recharge/pending" \
  -H "Authorization: Bearer $TOKEN" | jq -r '.[0].id')

APPROVE_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/wallet/recharge/$RECHARGE_ID/approve" \
  -H "Authorization: Bearer $TOKEN")

echo "✅ Wallet funded with 2000 EUR"
echo ""
read -p "Press Enter to continue..."
echo ""

# Step 7: Issue Ticket
echo "Step 7: Issuing ticket..."
TICKET_RESPONSE=$(curl -s -X POST "http://localhost:8081/api/v1/tickets/issue" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"bookingId\": \"$BOOKING_ID\"
  }")

TICKET_NUMBER=$(echo "$TICKET_RESPONSE" | jq -r '.ticketNumber')

if [ -z "$TICKET_NUMBER" ] || [ "$TICKET_NUMBER" = "null" ]; then
    echo "❌ Failed to issue ticket"
    echo "   Response: $TICKET_RESPONSE"
    exit 1
fi

echo "✅ Ticket issued: $TICKET_NUMBER"
echo ""
echo "Ticket details:"
echo "$TICKET_RESPONSE" | jq '{
    ticketNumber: .ticketNumber,
    status: .status,
    issuedAt: .issuedAt
}'
echo ""

# Summary
echo "========================================="
echo "  🎉 Booking Complete!"
echo "========================================="
echo ""
echo "Summary:"
echo "  Agency ID:      $AGENCY_ID"
echo "  Booking ID:     $BOOKING_ID"
echo "  Ticket Number:  $TICKET_NUMBER"
echo "  Price:          $OFFER_PRICE EUR"
echo ""
echo "What you can do next:"
echo ""
echo "1. View ticket details:"
echo "   curl -X GET \"http://localhost:8081/api/v1/tickets/$TICKET_NUMBER\" \\"
echo "     -H \"Authorization: Bearer $TOKEN\" | jq '.'"
echo ""
echo "2. Void the ticket (within 24 hours):"
echo "   curl -X POST \"http://localhost:8081/api/v1/tickets/$TICKET_NUMBER/void\" \\"
echo "     -H \"Authorization: Bearer $TOKEN\" | jq '.'"
echo ""
echo "3. Check wallet balance:"
echo "   curl -X GET \"http://localhost:8081/api/v1/wallet/$AGENCY_ID/balance\" \\"
echo "     -H \"Authorization: Bearer $TOKEN\" | jq '.'"
echo ""
echo "4. View all bookings:"
echo "   curl -X GET \"http://localhost:8081/api/v1/bookings\" \\"
echo "     -H \"Authorization: Bearer $TOKEN\" | jq '.'"
echo ""
echo "📖 For more information:"
echo "   - Full guide: docs/AMADEUS_INTEGRATION_GUIDE.md"
echo "   - Quick reference: docs/AMADEUS_QUICK_REFERENCE.md"
echo "   - Swagger UI: http://localhost:8081/swagger-ui.html"
echo ""
