# Amadeus API Integration Guide

## Overview

This guide explains how to integrate Amadeus Self-Service APIs into your B2B Flight Ticketing Platform. Your application already has the foundation in place - this guide will help you configure and use it properly.

## Table of Contents

1. [Getting Started with Amadeus](#getting-started-with-amadeus)
2. [Current Implementation Status](#current-implementation-status)
3. [Configuration Steps](#configuration-steps)
4. [Available APIs](#available-apis)
5. [Testing the Integration](#testing-the-integration)
6. [Production Deployment](#production-deployment)
7. [Troubleshooting](#troubleshooting)

---

## Getting Started with Amadeus

### 1. Create Amadeus Developer Account

1. Visit [Amadeus for Developers](https://developers.amadeus.com/)
2. Click "Register" and create a free account
3. Verify your email address
4. Log in to your dashboard

### 2. Create an Application

1. Go to [My Self-Service Workspace](https://developers.amadeus.com/my-apps)
2. Click "Create New App"
3. Fill in the application details:
   - **App Name**: B2B Flight Ticketing Platform
   - **Description**: B2B flight booking and ticketing system
4. Click "Create"

### 3. Get API Credentials

After creating your app, you'll see:
- **API Key**: Your client ID
- **API Secret**: Your client secret
- **Test Environment**: `https://test.api.amadeus.com`
- **Production Environment**: `https://api.amadeus.com`

**IMPORTANT**: Keep these credentials secure! Never commit them to version control.

---

## Current Implementation Status

Your application already has a complete Amadeus integration with:

### ✅ Implemented Features

1. **OAuth 2.0 Authentication** (`AmadeusAuthService.java`)
   - Automatic token management
   - Token caching with thread-safe access
   - Automatic token refresh
   - Mock mode for development without credentials

2. **Resilience Patterns** (`AmadeusClientImpl.java`)
   - Circuit Breaker (prevents cascade failures)
   - Retry with exponential backoff
   - Timeout protection
   - Graceful fallback handling

3. **Available API Operations**:
   - ✅ Flight Search (`searchFlights`)
   - ✅ Fare Rules (`getFareRules`)
   - ✅ Booking Creation (`createBooking`)
   - ✅ Ticket Issuance (`issueTicket`)
   - ✅ Ticket Void (`voidTicket`)
   - ✅ Ticket Refund (`refundTicket`)
   - ✅ Queue Messages (`getQueueMessages`)

4. **Mock Data Support**
   - Works without credentials for development
   - Automatic fallback to mock data
   - Realistic test responses

---

## Configuration Steps

### Step 1: Add Credentials to Environment

#### For Local Development (Docker Compose)

Edit your `.env` file:

```bash
# Amadeus API Configuration
AMADEUS_API_KEY=your_api_key_here
AMADEUS_API_SECRET=your_api_secret_here
AMADEUS_API_BASE_URL=https://test.api.amadeus.com
```

#### For Kubernetes Deployment

Update `k8s/secret.yaml`:

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: b2b-flight-secrets
  namespace: b2b-flight
type: Opaque
stringData:
  # ... existing secrets ...
  amadeus-api-key: "your_api_key_here"
  amadeus-api-secret: "your_api_secret_here"
```

Then update `k8s/app-deployment.yaml` to use these secrets:

```yaml
env:
  # ... existing env vars ...
  - name: AMADEUS_API_KEY
    valueFrom:
      secretKeyRef:
        name: b2b-flight-secrets
        key: amadeus-api-key
  - name: AMADEUS_API_SECRET
    valueFrom:
      secretKeyRef:
        name: b2b-flight-secrets
        key: amadeus-api-secret
  - name: AMADEUS_API_BASE_URL
    value: "https://test.api.amadeus.com"
```

### Step 2: Restart Your Application

#### Docker Compose
```bash
docker-compose down
docker-compose up -d
```

#### Kubernetes
```bash
kubectl apply -f k8s/secret.yaml
kubectl rollout restart deployment/b2b-flight-app -n b2b-flight
```

### Step 3: Verify Configuration

Check application logs:
```bash
# Docker
docker-compose logs app | grep -i amadeus

# Kubernetes
kubectl logs -f deployment/b2b-flight-app -n b2b-flight | grep -i amadeus
```

You should see:
```
Successfully authenticated with Amadeus API. Token expires in 1799 seconds
```

---

## Available APIs

### 1. Flight Search API

**Endpoint**: `POST /api/v1/flights/search`

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

**Example Request**:
```json
{
  "originLocationCode": "MAD",
  "destinationLocationCode": "NYC",
  "departureDate": "2026-03-15",
  "returnDate": "2026-03-22",
  "adults": 1,
  "children": 0,
  "infants": 0,
  "travelClass": "ECONOMY",
  "currencyCode": "EUR",
  "max": 10
}
```

**What It Does**:
- Searches for available flights
- Returns flight offers with pricing
- Includes airline, schedule, and fare details
- Applies agency markup automatically

### 2. Fare Rules API

**Endpoint**: `GET /api/v1/flights/fare-rules/{offerId}`

**Amadeus API Used**: [Flight Offers Price](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-offers-price)

**What It Does**:
- Gets detailed fare rules for a specific offer
- Shows cancellation policies
- Displays change fees
- Provides baggage allowances

### 3. Booking Creation API

**Endpoint**: `POST /api/v1/bookings`

**Amadeus API Used**: [Flight Create Orders](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-create-orders)

**What It Does**:
- Creates a PNR (Passenger Name Record) in Amadeus
- Reserves the flight
- Returns booking reference
- Holds the reservation for ticketing

### 4. Ticket Issuance API

**Endpoint**: `POST /api/v1/tickets/issue`

**Amadeus API Used**: [Flight Order Management](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-order-management)

**What It Does**:
- Issues e-tickets for confirmed bookings
- Generates ticket numbers
- Confirms payment
- Makes booking non-refundable (unless fare allows)

### 5. Ticket Void API

**Endpoint**: `POST /api/v1/tickets/{ticketNumber}/void`

**Amadeus API Used**: [Flight Order Management](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-order-management)

**What It Does**:
- Voids tickets within allowed time window (usually 24 hours)
- Full refund with no penalties
- Cancels the booking

### 6. Ticket Refund API

**Endpoint**: `POST /api/v1/tickets/{ticketNumber}/refund`

**Amadeus API Used**: [Flight Order Management](https://developers.amadeus.com/self-service/category/flights/api-doc/flight-order-management)

**What It Does**:
- Processes refunds according to fare rules
- Calculates penalties
- Returns refund amount
- Updates booking status

---

## Testing the Integration

### Test 1: Flight Search

```bash
# Get 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')

# Search for 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"
  }'
```

### Test 2: Check Amadeus Authentication

```bash
# Check application logs for authentication
docker-compose logs app | grep -A 5 "Amadeus"
```

Expected output:
```
Successfully authenticated with Amadeus API. Token expires in 1799 seconds
Using cached Amadeus access token
```

### Test 3: Health Check

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

Expected output:
```json
{
  "status": "UP"
}
```

---

## Production Deployment

### 1. Switch to Production Environment

Update your environment variables:

```bash
AMADEUS_API_BASE_URL=https://api.amadeus.com
AMADEUS_API_KEY=your_production_api_key
AMADEUS_API_SECRET=your_production_api_secret
```

### 2. Production Checklist

- [ ] Use production Amadeus credentials
- [ ] Store credentials in secure secret management (AWS Secrets Manager, HashiCorp Vault)
- [ ] Enable HTTPS/TLS for all API calls
- [ ] Configure proper rate limiting
- [ ] Set up monitoring and alerting
- [ ] Test all API endpoints thoroughly
- [ ] Review and adjust resilience patterns (circuit breaker thresholds)
- [ ] Enable audit logging for all transactions
- [ ] Set up backup and disaster recovery

### 3. Monitoring

Monitor these metrics:

- **Circuit Breaker State**: Should be CLOSED in normal operation
- **Retry Attempts**: Track how often retries occur
- **API Response Times**: Should be under 10 seconds
- **Error Rates**: Should be below 5%
- **Token Refresh**: Should happen automatically

Access metrics:
```bash
curl http://localhost:8081/actuator/metrics/resilience4j.circuitbreaker.state
curl http://localhost:8081/actuator/metrics/resilience4j.retry.calls
```

---

## Troubleshooting

### Issue 1: "Amadeus API credentials not configured"

**Symptom**: Application uses mock data instead of real API

**Solution**:
1. Check `.env` file has correct credentials
2. Restart application: `docker-compose restart app`
3. Verify environment variables: `docker-compose exec app env | grep AMADEUS`

### Issue 2: "Failed to authenticate with Amadeus API"

**Symptom**: 401 Unauthorized errors

**Solution**:
1. Verify API key and secret are correct
2. Check if credentials are for correct environment (test vs production)
3. Ensure no extra spaces in credentials
4. Try regenerating credentials in Amadeus dashboard

### Issue 3: Circuit Breaker Opens

**Symptom**: "Circuit breaker is OPEN" errors

**Solution**:
1. Check Amadeus API status: https://developers.amadeus.com/status
2. Review error logs: `docker-compose logs app | grep -i error`
3. Wait for circuit breaker to auto-recover (10 seconds)
4. Adjust circuit breaker settings in `application.yml` if needed

### Issue 4: Timeout Errors

**Symptom**: "Request timed out" after 10 seconds

**Solution**:
1. Check network connectivity
2. Verify Amadeus API is responding
3. Increase timeout in `application.yml`:
   ```yaml
   resilience4j:
     timelimiter:
       instances:
         amadeus:
           timeoutDuration: 15s
   ```

### Issue 5: Rate Limiting

**Symptom**: 429 Too Many Requests

**Solution**:
1. Amadeus Test API has rate limits (check your plan)
2. Implement request throttling in your application
3. Upgrade to higher tier plan if needed
4. Use caching to reduce API calls

---

## Amadeus API Documentation

### Official Resources

- **Developer Portal**: https://developers.amadeus.com/
- **API Reference**: https://developers.amadeus.com/self-service
- **Getting Started**: https://developers.amadeus.com/get-started/get-started-with-self-service-apis-335
- **Code Examples**: https://github.com/amadeus4dev
- **Support**: https://developers.amadeus.com/support

### Key APIs for Flight Ticketing

1. **Flight Offers Search**: Search for flights
   - https://developers.amadeus.com/self-service/category/flights/api-doc/flight-offers-search

2. **Flight Offers Price**: Get detailed pricing and fare rules
   - https://developers.amadeus.com/self-service/category/flights/api-doc/flight-offers-price

3. **Flight Create Orders**: Create bookings
   - https://developers.amadeus.com/self-service/category/flights/api-doc/flight-create-orders

4. **Flight Order Management**: Manage bookings, issue tickets, void, refund
   - https://developers.amadeus.com/self-service/category/flights/api-doc/flight-order-management

5. **Airport & City Search**: Search for airports and cities
   - https://developers.amadeus.com/self-service/category/flights/api-doc/airport-and-city-search

---

## Next Steps

1. **Get Amadeus Credentials**: Sign up at https://developers.amadeus.com/
2. **Configure Your Application**: Add credentials to `.env` file
3. **Test Flight Search**: Use the test script above
4. **Explore Swagger UI**: http://localhost:8081/swagger-ui.html
5. **Review API Documentation**: Check Amadeus docs for advanced features
6. **Implement Additional Features**: Add more Amadeus APIs as needed

---

## Support

For issues with:
- **Amadeus API**: Contact Amadeus support at https://developers.amadeus.com/support
- **Your Application**: Check logs and review this guide
- **Integration Questions**: Review the code in `src/main/java/com/flightticket/client/amadeus/`

---

**Last Updated**: January 2026
**Version**: 1.0
