# B2B Flight Ticketing Platform - Deployment Guide

This guide provides comprehensive instructions for deploying the B2B Flight Ticketing Platform in different environments.

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Environment Variables](#environment-variables)
3. [Local Development Deployment](#local-development-deployment)
4. [Docker Deployment](#docker-deployment)
5. [Kubernetes Deployment](#kubernetes-deployment)
6. [Database Migration](#database-migration)
7. [Keycloak Configuration](#keycloak-configuration)
8. [Amadeus API Setup](#amadeus-api-setup)
9. [Post-Deployment Verification](#post-deployment-verification)
10. [Troubleshooting](#troubleshooting)

## Prerequisites

### Required Software

- **Java 17+**: OpenJDK or Oracle JDK
- **Maven 3.8+**: For building the application
- **Docker 20.10+**: For containerized deployment
- **Docker Compose 2.0+**: For local development
- **PostgreSQL 15+**: Database server
- **Redis 7+**: Caching and session management
- **RabbitMQ 3+**: Message queue
- **Keycloak 23+**: Authentication and authorization

### Optional Software

- **Kubernetes 1.24+**: For production deployment
- **kubectl**: Kubernetes command-line tool
- **Helm 3+**: Kubernetes package manager (optional)

## Environment Variables

The application uses environment variables for configuration. See `.env.example` for a complete list.

### Required Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `AMADEUS_API_KEY` | Amadeus API client ID | `your_api_key` |
| `AMADEUS_API_SECRET` | Amadeus API client secret | `your_api_secret` |
| `ENCRYPTION_SECRET_KEY` | Base64-encoded encryption key | Generate using `EncryptionUtil.generateBase64Key()` |

### Optional Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `SPRING_PROFILE` | Active Spring profile | `dev` |
| `SERVER_PORT` | Application port | `8081` |
| `SPRING_DATASOURCE_URL` | Database connection URL | `jdbc:postgresql://localhost:5432/flight_platform` |
| `SPRING_DATASOURCE_USERNAME` | Database username | `flight_user` |
| `SPRING_DATASOURCE_PASSWORD` | Database password | `flight_pass` |
| `SPRING_REDIS_HOST` | Redis host | `localhost` |
| `SPRING_REDIS_PORT` | Redis port | `6379` |
| `SPRING_RABBITMQ_HOST` | RabbitMQ host | `localhost` |
| `SPRING_RABBITMQ_PORT` | RabbitMQ port | `5672` |
| `SPRING_RABBITMQ_USERNAME` | RabbitMQ username | `flight_user` |
| `SPRING_RABBITMQ_PASSWORD` | RabbitMQ password | `flight_pass` |
| `KEYCLOAK_AUTH_SERVER_URL` | Keycloak server URL | `http://localhost:8080` |
| `KEYCLOAK_REALM` | Keycloak realm name | `b2b-flight-platform` |
| `KEYCLOAK_CLIENT_ID` | Keycloak client ID | `b2b-flight-backend` |
| `KEYCLOAK_CLIENT_SECRET` | Keycloak client secret | `b2b-flight-backend-secret` |

### Generating Encryption Key

The encryption key is used to encrypt sensitive data at rest (passwords, passport numbers, etc.).

```java
// Run this code to generate a secure encryption key
import com.flightticket.util.EncryptionUtil;

public class KeyGenerator {
    public static void main(String[] args) {
        String key = EncryptionUtil.generateBase64Key();
        System.out.println("ENCRYPTION_SECRET_KEY=" + key);
    }
}
```

Or use the following command:
```bash
mvn exec:java -Dexec.mainClass="com.flightticket.util.EncryptionUtil" -Dexec.args="generateKey"
```

**IMPORTANT**: Store this key securely and never commit it to version control. In production, use a secret management service like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault.

## Local Development Deployment

### 1. Clone the Repository

```bash
git clone <repository-url>
cd b2b-flight-platform
```

### 2. Configure Environment Variables

```bash
cp .env.example .env
# Edit .env and fill in your credentials
```

### 3. Start Infrastructure Services

```bash
docker-compose up -d postgres redis rabbitmq keycloak
```

Wait for services to be healthy:
```bash
docker-compose ps
```

### 4. Build the Application

```bash
mvn clean package -DskipTests
```

### 5. Run Database Migrations

Migrations run automatically on application startup, but you can run them manually:

```bash
mvn flyway:migrate
```

### 6. Start the Application

```bash
java -jar target/b2b-flight-platform-1.0.0-SNAPSHOT.jar
```

Or using Maven:
```bash
mvn spring-boot:run
```

### 7. Access the Application

- **Application**: http://localhost:8081
- **Swagger UI**: http://localhost:8081/swagger-ui.html
- **Actuator Health**: http://localhost:8081/actuator/health
- **Keycloak Admin**: http://localhost:8080 (admin/admin)
- **RabbitMQ Management**: http://localhost:15672 (flight_user/flight_pass)

## Docker Deployment

### Database Initialization

The PostgreSQL container is configured to create two databases on first startup:
- `flight_platform`: Main application database
- `keycloak`: Keycloak authentication database

This is handled automatically by the `scripts/init-databases.sh` script mounted in the container.

### 1. Build Docker Image

```bash
docker build -t b2b-flight-platform:latest .
```

### 2. Start All Services

```bash
docker-compose up -d
```

This will start:
- PostgreSQL database
- Redis cache
- RabbitMQ message queue
- Keycloak authentication server
- Application server

### 3. View Logs

```bash
# All services
docker-compose logs -f

# Specific service
docker-compose logs -f app
```

### 4. Stop Services

```bash
docker-compose down
```

To remove volumes (data will be lost):
```bash
docker-compose down -v
```

## Kubernetes Deployment

See [k8s/README.md](../k8s/README.md) for detailed Kubernetes deployment instructions.

### Quick Start

```bash
# Create namespace
kubectl apply -f k8s/namespace.yaml

# Configure secrets (edit first!)
kubectl apply -f k8s/secret.yaml
kubectl apply -f k8s/configmap.yaml

# Deploy infrastructure
kubectl apply -f k8s/postgres-deployment.yaml
kubectl apply -f k8s/redis-deployment.yaml
kubectl apply -f k8s/rabbitmq-deployment.yaml
kubectl apply -f k8s/keycloak-deployment.yaml

# Wait for services to be ready
kubectl wait --for=condition=ready pod -l app=postgres -n b2b-flight-platform --timeout=300s

# Deploy application
kubectl apply -f k8s/app-deployment.yaml

# Deploy ingress (optional)
kubectl apply -f k8s/ingress.yaml
```

## Database Migration

The application uses Flyway for database migrations. Migrations are located in `src/main/resources/db/migration/`.

### Automatic Migration

Migrations run automatically on application startup when `spring.flyway.enabled=true` (default).

### Manual Migration

To run migrations manually:

```bash
# Using Maven
mvn flyway:migrate

# Using Docker
docker-compose exec app java -jar app.jar --spring.flyway.enabled=true

# Using Kubernetes
kubectl exec -it deployment/b2b-flight-app -n b2b-flight-platform -- \
  java -jar app.jar --spring.flyway.enabled=true
```

### Migration Files

- `V1__create_initial_schema.sql`: Creates initial database schema
- `V2__create_rate_limiting_tables.sql`: Creates rate limiting tables
- `V3__create_queue_messages_table.sql`: Creates queue management tables

### Rollback

Flyway Community Edition does not support automatic rollback. To rollback:

1. Restore database from backup
2. Or manually write and execute rollback SQL scripts

## Keycloak Configuration

### Initial Setup

1. **Access Keycloak Admin Console**
   - URL: http://localhost:8080 (or your Keycloak URL)
   - Username: `admin`
   - Password: `admin`

2. **Create Realm**
   - Click "Create Realm"
   - Name: `b2b-flight-platform`
   - Click "Create"

3. **Create Client**
   - Navigate to Clients → Create Client
   - Client ID: `b2b-flight-backend`
   - Client Protocol: `openid-connect`
   - Click "Next"
   - Client authentication: `ON`
   - Authorization: `OFF`
   - Authentication flow: Enable "Standard flow" and "Direct access grants"
   - Click "Save"
   - Go to "Credentials" tab
   - Copy the "Client Secret" and set it as `KEYCLOAK_CLIENT_SECRET`

4. **Create Roles**
   - Navigate to Realm Roles → Create Role
   - Create the following roles:
     - `SUPER_ADMIN`
     - `AGENCY_ADMIN`
     - `HR_USER`
     - `FINANCE_USER`
     - `AGENT`

5. **Configure MFA (Optional but Recommended)**
   - Navigate to Authentication → Required Actions
   - Enable "Configure OTP"
   - Navigate to Authentication → Flows
   - Configure "Browser" flow to require OTP for admin roles

6. **Create Initial Super Admin User**
   - Navigate to Users → Add User
   - Username: `superadmin`
   - Email: `admin@example.com`
   - Email Verified: `ON`
   - Click "Create"
   - Go to "Credentials" tab
   - Set password (temporary: OFF)
   - Go to "Role Mappings" tab
   - Assign "SUPER_ADMIN" role

### Automated Configuration

You can use the Keycloak Admin REST API or the provided realm configuration file:

```bash
# Import realm configuration
docker-compose exec keycloak /opt/keycloak/bin/kc.sh import \
  --file /opt/keycloak/data/import/realm-config.json
```

See `keycloak/realm-config.json` for the complete realm configuration.

## Amadeus API Setup

### 1. Create Amadeus Account

1. Go to https://developers.amadeus.com/
2. Sign up for a free account
3. Create a new application

### 2. Get API Credentials

1. Navigate to your application dashboard
2. Copy your API Key (Client ID)
3. Copy your API Secret (Client Secret)

### 3. Configure Environment Variables

```bash
export AMADEUS_API_KEY="your_api_key_here"
export AMADEUS_API_SECRET="your_api_secret_here"
```

Or add to `.env` file:
```
AMADEUS_API_KEY=your_api_key_here
AMADEUS_API_SECRET=your_api_secret_here
```

### 4. Test API Connection

The application will test the Amadeus API connection on startup. Check the logs:

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

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

### 5. API Environments

- **Test Environment**: `https://test.api.amadeus.com` (default)
- **Production Environment**: `https://api.amadeus.com`

Set the environment using:
```bash
export AMADEUS_API_BASE_URL=https://api.amadeus.com
```

## Post-Deployment Verification

### 1. Health Check

```bash
curl http://localhost:8081/actuator/health
```

Expected response:
```json
{
  "status": "UP",
  "components": {
    "db": {"status": "UP"},
    "redis": {"status": "UP"},
    "amadeus": {"status": "UP"}
  }
}
```

### 2. API Documentation

Access Swagger UI at: http://localhost:8081/swagger-ui.html

### 3. Test Authentication

```bash
# Get access token
curl -X POST http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" \
  -d "username=superadmin" \
  -d "password=your_password" \
  -d "grant_type=password"
```

### 4. Test API Endpoint

```bash
# Replace {token} with the access token from previous step
curl -X GET http://localhost:8081/api/health \
  -H "Authorization: Bearer {token}"
```

### 5. Verify Database

```bash
# Docker
docker-compose exec postgres psql -U flight_user -d flight_platform -c "\dt"

# Kubernetes
kubectl exec -it deployment/postgres -n b2b-flight-platform -- \
  psql -U flight_user -d flight_platform -c "\dt"
```

### 6. Check Logs

```bash
# Docker
docker-compose logs -f app

# Kubernetes
kubectl logs -f deployment/b2b-flight-app -n b2b-flight-platform
```

## Troubleshooting

### Database Connection Failed

**Problem**: Application fails to start with database connection error.

**Solution**:
1. Check if PostgreSQL is running: `docker-compose ps postgres`
2. Verify database credentials in environment variables
3. Check database logs: `docker-compose logs postgres`
4. Verify both databases exist:
   ```bash
   docker-compose exec postgres psql -U flight_user -c "\l"
   ```
   You should see both `flight_platform` and `keycloak` databases.

### Keycloak Connection Failed

**Problem**: Application can't connect to Keycloak.

**Solution**:
1. Check if Keycloak is running: `docker-compose ps keycloak`
2. Verify Keycloak URL in environment variables
3. Check Keycloak logs: `docker-compose logs keycloak`
4. Ensure realm and client are configured correctly

### Amadeus API Errors

**Problem**: Amadeus API calls fail.

**Solution**:
1. Verify API credentials are correct
2. Check if you're using the correct environment (test vs production)
3. Check API quota limits on Amadeus dashboard
4. Review application logs for detailed error messages

### Database Migration Failed

**Problem**: Flyway migration fails.

**Solution**:
1. Check migration scripts for syntax errors
2. Verify database user has sufficient permissions
3. Check Flyway schema history: `SELECT * FROM flyway_schema_history;`
4. If needed, repair Flyway: `mvn flyway:repair`

### Out of Memory Errors

**Problem**: Application crashes with OutOfMemoryError.

**Solution**:
1. Increase JVM heap size: `JAVA_OPTS="-Xmx2g -Xms1g"`
2. Check for memory leaks in application logs
3. Increase Docker container memory limits
4. Increase Kubernetes pod resource limits

### Port Already in Use

**Problem**: Application fails to start because port is already in use.

**Solution**:
1. Change application port: `SERVER_PORT=8082`
2. Or stop the process using the port:
   ```bash
   # Find process
   lsof -i :8081
   # Kill process
   kill -9 <PID>
   ```

### SSL/TLS Certificate Errors

**Problem**: SSL certificate validation fails.

**Solution**:
1. For development, you can disable SSL verification (not recommended for production)
2. Import certificates into Java keystore
3. Use proper certificates from a trusted CA in production

## Production Deployment Checklist

- [ ] Use production-grade database (managed PostgreSQL)
- [ ] Configure database backups
- [ ] Use external secret management (Vault, AWS Secrets Manager)
- [ ] Enable SSL/TLS for all connections
- [ ] Configure proper logging and monitoring
- [ ] Set up alerting for critical errors
- [ ] Configure auto-scaling
- [ ] Implement disaster recovery plan
- [ ] Perform security audit
- [ ] Configure rate limiting
- [ ] Set up CDN for static assets
- [ ] Configure proper CORS policies
- [ ] Enable database connection pooling
- [ ] Configure session timeout
- [ ] Set up log aggregation (ELK, Splunk)
- [ ] Configure metrics collection (Prometheus)
- [ ] Set up distributed tracing (Jaeger, Zipkin)
- [ ] Perform load testing
- [ ] Document runbooks for common issues
- [ ] Train operations team

## Support

For issues and questions:
- Check application logs
- Review Swagger API documentation
- Consult the [API Documentation](API_DOCUMENTATION.md)
- Review [Resilience Patterns](RESILIENCE_PATTERNS.md)
- Review [Transaction Management](TRANSACTION_MANAGEMENT.md)

## Security Considerations

1. **Never commit secrets to version control**
2. **Use strong passwords for all services**
3. **Enable MFA for admin accounts**
4. **Regularly update dependencies**
5. **Monitor for security vulnerabilities**
6. **Implement network segmentation**
7. **Use least privilege principle**
8. **Enable audit logging**
9. **Regularly backup data**
10. **Implement rate limiting**
11. **Use HTTPS in production**
12. **Validate all inputs**
13. **Encrypt sensitive data at rest and in transit**
14. **Regularly review access logs**
15. **Implement intrusion detection**
