# Amadeus API Integration - Complete Guide

## 🚀 Quick Start

Your B2B Flight Ticketing Platform is **already integrated** with Amadeus API! You just need to configure your credentials.

### 3-Step Setup

```bash
# 1. Setup credentials
./setup-amadeus.sh

# 2. Test integration
./test-amadeus-integration.sh

# 3. Try your first booking
./first-booking-tutorial.sh
```

---

## 📚 Documentation

### For Getting Started
- **[Integration Guide](docs/AMADEUS_INTEGRATION_GUIDE.md)** - Complete setup and configuration guide
- **[Quick Reference](docs/AMADEUS_QUICK_REFERENCE.md)** - Common commands and API calls
- **[First Booking Tutorial](docs/AMADEUS_FIRST_BOOKING_TUTORIAL.md)** - Step-by-step booking walkthrough

### For Development
- **[API Documentation](http://localhost:8081/swagger-ui.html)** - Interactive API explorer
- **[Resilience Patterns](docs/RESILIENCE_PATTERNS.md)** - Circuit breaker, retry, timeout patterns
- **[Deployment Guide](docs/DEPLOYMENT.md)** - Production deployment instructions

---

## ✅ What's Already Implemented

Your application has a **complete Amadeus integration** with:

### 1. Authentication & Security
- ✅ OAuth 2.0 client credentials flow
- ✅ Automatic token management and refresh
- ✅ Thread-safe token caching
- ✅ Secure credential storage

### 2. Resilience Patterns
- ✅ **Circuit Breaker** - Prevents cascade failures
- ✅ **Retry with Exponential Backoff** - Automatic retry on transient failures
- ✅ **Timeout Protection** - Prevents hanging requests
- ✅ **Graceful Fallback** - Mock data when API unavailable

### 3. Available APIs
- ✅ **Flight Search** - Search for available flights
- ✅ **Fare Rules** - Get cancellation policies and baggage info
- ✅ **Booking Creation** - Create PNR in Amadeus
- ✅ **Ticket Issuance** - Issue e-tickets
- ✅ **Ticket Void** - Void tickets within 24 hours
- ✅ **Ticket Refund** - Process refunds with penalties
- ✅ **Queue Management** - Retrieve queue messages

### 4. Monitoring & Health Checks
- ✅ Health endpoints for Amadeus API status
- ✅ Circuit breaker state monitoring
- ✅ Prometheus metrics export
- ✅ Detailed logging

---

## 🔧 Configuration

### Get Amadeus Credentials

1. Visit [Amadeus for Developers](https://developers.amadeus.com/)
2. Create a free account
3. Create a new app
4. Copy your API Key and API Secret

### Configure Your Application

#### Option 1: Using Setup Script (Recommended)
```bash
./setup-amadeus.sh
```

#### Option 2: Manual Configuration
Edit `.env` file:
```bash
AMADEUS_API_KEY=your_api_key_here
AMADEUS_API_SECRET=your_api_secret_here
AMADEUS_API_BASE_URL=https://test.api.amadeus.com
```

Then restart:
```bash
docker-compose restart app
```

---

## 🧪 Testing

### Test 1: Integration Test
```bash
./test-amadeus-integration.sh
```

This will check:
- Application health
- Amadeus API authentication
- Circuit breaker status
- Recent errors

### Test 2: Flight Search
```bash
# Get 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')

# Search flights
curl -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"
  }' | jq '.'
```

### Test 3: Complete Booking Flow
```bash
./first-booking-tutorial.sh
```

---

## 📊 Monitoring

### Health Check
```bash
curl http://localhost:8081/actuator/health | jq
```

### Amadeus API Status
```bash
curl http://localhost:8081/actuator/health | jq '.components.amadeusApi'
```

### Circuit Breaker Status
```bash
curl http://localhost:8081/actuator/health | jq '.components.circuitBreakers.details.amadeus'
```

### View Logs
```bash
# All Amadeus logs
docker-compose logs app | grep -i amadeus

# Authentication logs
docker-compose logs app | grep -i "amadeus" | grep -i "auth"

# Error logs
docker-compose logs app | grep -i "amadeus" | grep -i "error"
```

---

## 🏗️ Architecture

### Components

```
┌─────────────────────────────────────────────────────────┐
│                   Your Application                       │
│                                                          │
│  ┌────────────────────────────────────────────────┐    │
│  │         Flight Search Controller               │    │
│  └──────────────────┬─────────────────────────────┘    │
│                     │                                    │
│  ┌──────────────────▼─────────────────────────────┐    │
│  │         Flight Search Service                  │    │
│  └──────────────────┬─────────────────────────────┘    │
│                     │                                    │
│  ┌──────────────────▼─────────────────────────────┐    │
│  │         Amadeus Client (with Resilience)       │    │
│  │  - Circuit Breaker                             │    │
│  │  - Retry with Exponential Backoff              │    │
│  │  - Timeout Protection                          │    │
│  └──────────────────┬─────────────────────────────┘    │
│                     │                                    │
│  ┌──────────────────▼─────────────────────────────┐    │
│  │         Amadeus Auth Service                   │    │
│  │  - OAuth 2.0 Token Management                  │    │
│  │  - Token Caching                               │    │
│  │  - Automatic Refresh                           │    │
│  └──────────────────┬─────────────────────────────┘    │
│                     │                                    │
└─────────────────────┼────────────────────────────────────┘
                      │
                      │ HTTPS
                      │
┌─────────────────────▼────────────────────────────────────┐
│              Amadeus Self-Service API                     │
│         https://test.api.amadeus.com                      │
└───────────────────────────────────────────────────────────┘
```

### Request Flow

1. **User Request** → Controller receives flight search request
2. **Service Layer** → Validates and processes request
3. **Amadeus Client** → Applies resilience patterns
4. **Auth Service** → Gets/refreshes OAuth token
5. **API Call** → Makes authenticated request to Amadeus
6. **Response** → Returns flight offers to user

---

## 🔒 Security Best Practices

### ✅ Implemented
- OAuth 2.0 authentication
- Secure credential storage in environment variables
- HTTPS for all API calls
- JWT authentication for your API
- Role-based access control

### 📋 Recommendations
- Use secret management service in production (AWS Secrets Manager, HashiCorp Vault)
- Rotate credentials regularly
- Monitor for suspicious activity
- Enable audit logging
- Use production credentials only in production

---

## 🚀 Production Deployment

### Checklist

- [ ] Get production Amadeus credentials
- [ ] Update environment variables:
  ```bash
  AMADEUS_API_BASE_URL=https://api.amadeus.com
  AMADEUS_API_KEY=production_key
  AMADEUS_API_SECRET=production_secret
  ```
- [ ] Store credentials in secure secret management
- [ ] Test all endpoints in test environment
- [ ] Configure monitoring and alerts
- [ ] Set up log aggregation
- [ ] Review and adjust resilience patterns
- [ ] Enable HTTPS/TLS
- [ ] Configure rate limiting
- [ ] Set up backup and disaster recovery

### Environment URLs

- **Test**: `https://test.api.amadeus.com` (Free tier available)
- **Production**: `https://api.amadeus.com` (Paid plans)

---

## 📖 API Reference

### Flight Search
- **Endpoint**: `POST /api/v1/flights/search`
- **Amadeus API**: [Flight Offers Search](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-offers-search)

### Fare Rules
- **Endpoint**: `GET /api/v1/flights/fare-rules/{offerId}`
- **Amadeus API**: [Flight Offers Price](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-offers-price)

### Booking Creation
- **Endpoint**: `POST /api/v1/bookings`
- **Amadeus API**: [Flight Create Orders](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-create-orders)

### Ticket Issuance
- **Endpoint**: `POST /api/v1/tickets/issue`
- **Amadeus API**: [Flight Order Management](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-order-management)

---

## 🆘 Troubleshooting

### Issue: "Amadeus API credentials not configured"
**Solution**: Run `./setup-amadeus.sh` or manually edit `.env` file

### Issue: "Failed to authenticate with Amadeus API"
**Solution**: 
1. Verify credentials are correct
2. Check for extra spaces
3. Ensure using correct environment (test vs production)
4. Restart application

### Issue: Circuit Breaker Open
**Solution**:
1. Wait 10 seconds for auto-recovery
2. Check Amadeus API status
3. Review error logs

### Issue: Timeout Errors
**Solution**:
1. Check network connectivity
2. Verify Amadeus API is responding
3. Increase timeout in `application.yml`

---

## 📞 Support

### Amadeus Support
- **Developer Portal**: https://developers.amadeus.com/
- **Support**: https://developers.amadeus.com/support
- **API Status**: https://developers.amadeus.com/status
- **Documentation**: https://developers.amadeus.com/self-service

### Your Application
- **Swagger UI**: http://localhost:8081/swagger-ui.html
- **Health Check**: http://localhost:8081/actuator/health
- **Logs**: `docker-compose logs app`

---

## 🎯 Next Steps

1. **Get Credentials**: Sign up at https://developers.amadeus.com/
2. **Configure**: Run `./setup-amadeus.sh`
3. **Test**: Run `./test-amadeus-integration.sh`
4. **Learn**: Try `./first-booking-tutorial.sh`
5. **Explore**: Open http://localhost:8081/swagger-ui.html
6. **Read**: Check `docs/AMADEUS_INTEGRATION_GUIDE.md`
7. **Deploy**: Follow production deployment checklist

---

## 📝 Files Overview

### Scripts
- `setup-amadeus.sh` - Interactive setup wizard
- `test-amadeus-integration.sh` - Integration test suite
- `first-booking-tutorial.sh` - Complete booking walkthrough

### Documentation
- `docs/AMADEUS_INTEGRATION_GUIDE.md` - Complete integration guide
- `docs/AMADEUS_QUICK_REFERENCE.md` - Quick command reference
- `docs/AMADEUS_FIRST_BOOKING_TUTORIAL.md` - Detailed tutorial
- `docs/RESILIENCE_PATTERNS.md` - Resilience patterns documentation

### Configuration
- `.env` - Environment variables (add your credentials here)
- `application.yml` - Application configuration
- `docker-compose.yml` - Docker services configuration

### Source Code
- `src/main/java/com/flightticket/client/amadeus/` - Amadeus client implementation
- `src/main/java/com/flightticket/config/` - Configuration classes
- `src/main/java/com/flightticket/controller/` - REST controllers

---

**Last Updated**: January 2026  
**Version**: 1.0  
**Status**: Production Ready ✅

---

## 🎉 You're All Set!

Your application is ready to integrate with Amadeus API. Just add your credentials and start booking flights!

```bash
./setup-amadeus.sh
```

Happy coding! ✈️
