#!/bin/bash

# Test Amadeus API Credentials
# This script tests if your Amadeus API credentials are valid

echo "=========================================="
echo "Testing Amadeus API Credentials"
echo "=========================================="
echo ""

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

echo "API Key: $AMADEUS_API_KEY"
echo "API Secret: ${AMADEUS_API_SECRET:0:5}***"
echo "Base URL: $AMADEUS_API_BASE_URL"
echo ""
echo "Testing authentication..."
echo ""

# Test authentication
response=$(curl -s -w "\n%{http_code}" -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")

# Extract HTTP status code (last line)
http_code=$(echo "$response" | tail -n1)
# Extract response body (all but last line)
body=$(echo "$response" | sed '$d')

echo "HTTP Status: $http_code"
echo ""

if [ "$http_code" = "200" ]; then
    echo "✅ SUCCESS! Your Amadeus credentials are valid."
    echo ""
    echo "Access Token Response:"
    echo "$body" | python3 -m json.tool 2>/dev/null || echo "$body"
    echo ""
    echo "You can now restart your application:"
    echo "  docker-compose restart app"
else
    echo "❌ FAILED! Your Amadeus credentials are invalid."
    echo ""
    echo "Error Response:"
    echo "$body"
    echo ""
    echo "Please check your credentials at:"
    echo "  https://developers.amadeus.com/my-apps"
    echo ""
    echo "Then update the .env file with the correct:"
    echo "  - AMADEUS_API_KEY"
    echo "  - AMADEUS_API_SECRET"
fi

echo ""
echo "=========================================="
