#!/bin/bash

echo "========================================="
echo "  Amadeus Credentials Configuration"
echo "========================================="
echo ""
echo "This script will securely add your Amadeus"
echo "API credentials to the .env file."
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo "Creating .env file from .env.example..."
    cp .env.example .env
fi

echo "Please enter your Amadeus API credentials:"
echo ""
read -p "API Key (Client ID): " API_KEY
read -sp "API Secret: " API_SECRET
echo ""
echo ""

# Validate inputs
if [ -z "$API_KEY" ] || [ -z "$API_SECRET" ]; then
    echo "❌ Error: API Key and Secret cannot be empty"
    exit 1
fi

# Update .env file
echo "Updating .env file..."

# Backup existing .env
cp .env .env.backup

# Update or add Amadeus credentials
if grep -q "AMADEUS_API_KEY=" .env; then
    # Update existing
    sed -i.tmp "s|AMADEUS_API_KEY=.*|AMADEUS_API_KEY=$API_KEY|g" .env
    sed -i.tmp "s|AMADEUS_API_SECRET=.*|AMADEUS_API_SECRET=$API_SECRET|g" .env
    sed -i.tmp "s|AMADEUS_API_BASE_URL=.*|AMADEUS_API_BASE_URL=https://test.api.amadeus.com|g" .env
    rm .env.tmp 2>/dev/null
else
    # Add new
    echo "" >> .env
    echo "# Amadeus API Configuration" >> .env
    echo "AMADEUS_API_KEY=$API_KEY" >> .env
    echo "AMADEUS_API_SECRET=$API_SECRET" >> .env
    echo "AMADEUS_API_BASE_URL=https://test.api.amadeus.com" >> .env
fi

echo "✅ Credentials saved to .env file"
echo ""

# Rebuild and restart application
echo "Rebuilding application..."
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✅ Build successful"
echo ""

echo "Restarting application..."
docker-compose stop app
docker-compose rm -f app
docker-compose up -d app

echo ""
echo "⏳ Waiting for application to start (30 seconds)..."
sleep 30

echo ""
echo "Checking Amadeus authentication..."
docker-compose logs app | grep -i "amadeus" | grep -i "auth" | tail -5

echo ""
echo "========================================="
echo "  Configuration Complete! ✅"
echo "========================================="
echo ""
echo "Your Amadeus API is now configured."
echo ""
echo "Next steps:"
echo "  1. Test integration: ./test-amadeus-integration.sh"
echo "  2. Try first booking: ./first-booking-tutorial.sh"
echo ""
