# API Documentation

## Overview

The B2B Flight Ticketing Platform provides comprehensive REST API documentation using OpenAPI 3.0 (Swagger). The documentation is automatically generated from code annotations and provides interactive testing capabilities.

## Accessing the Documentation

### Swagger UI

Once the application is running, you can access the interactive Swagger UI at:

```
http://localhost:8081/swagger-ui.html
```

The Swagger UI provides:
- Complete list of all API endpoints
- Request/response schemas with examples
- Interactive "Try it out" functionality
- Authentication support for testing secured endpoints
- Detailed descriptions of all operations

### OpenAPI JSON Specification

The raw OpenAPI specification in JSON format is available at:

```
http://localhost:8081/api-docs
```

This endpoint can be used to:
- Import the API specification into tools like Postman or Insomnia
- Generate client SDKs using OpenAPI Generator
- Integrate with API management platforms

## API Structure

### Base URL

```
http://localhost:8081/api/v1
```

### Authentication

All endpoints (except `/api/v1/auth/login`) require JWT authentication:

1. **Obtain Token**: Call `POST /api/v1/auth/login` with credentials
2. **Use Token**: Include in Authorization header: `Bearer {token}`
3. **MFA Required**: Admin roles (SUPER_ADMIN, AGENCY_ADMIN) require MFA code

Example:
```bash
# Login
curl -X POST http://localhost:8081/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "password123",
    "mfaCode": "123456"
  }'

# Use token
curl -X GET http://localhost:8081/api/v1/agencies \
  -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."
```

## API Endpoints by Category

### Authentication
- `POST /api/v1/auth/login` - User login
- `POST /api/v1/auth/refresh` - Refresh access token
- `POST /api/v1/auth/logout` - User logout
- `POST /api/v1/auth/mfa/setup` - Setup MFA
- `POST /api/v1/auth/mfa/verify` - Verify MFA code

### Agency Management
- `POST /api/v1/agencies` - Create new agency (SUPER_ADMIN)
- `GET /api/v1/agencies` - Get all agencies (SUPER_ADMIN)
- `GET /api/v1/agencies/{agencyId}` - Get agency by ID
- `PUT /api/v1/agencies/{agencyId}` - Update agency (SUPER_ADMIN)
- `POST /api/v1/agencies/{agencyId}/verify` - Verify agency (SUPER_ADMIN)
- `POST /api/v1/agencies/{agencyId}/activate` - Activate agency (SUPER_ADMIN)
- `POST /api/v1/agencies/{agencyId}/deactivate` - Deactivate agency (SUPER_ADMIN)
- `PUT /api/v1/agencies/{agencyId}/markup` - Update markup (SUPER_ADMIN)
- `POST /api/v1/agencies/{agencyId}/payment` - Record payment (SUPER_ADMIN)
- `POST /api/v1/agencies/{agencyId}/renew` - Renew subscription (SUPER_ADMIN)
- `GET /api/v1/agencies/pending-verification` - Get pending agencies (SUPER_ADMIN)
- `GET /api/v1/agencies/expiring` - Get expiring agencies (SUPER_ADMIN)

### User Management
- `POST /api/v1/users` - Create user
- `GET /api/v1/users` - Get all users
- `GET /api/v1/users/{userId}` - Get user by ID
- `PUT /api/v1/users/{userId}` - Update user
- `DELETE /api/v1/users/{userId}` - Delete user
- `POST /api/v1/users/{userId}/roles` - Assign role
- `DELETE /api/v1/users/{userId}/roles/{role}` - Revoke role

### Wallet Management
- `GET /api/v1/wallets/agency/{agencyId}` - Get wallet balance
- `POST /api/v1/wallets/recharge` - Request recharge
- `POST /api/v1/wallets/recharge/{requestId}/approve` - Approve recharge (SUPER_ADMIN)
- `POST /api/v1/wallets/recharge/{requestId}/reject` - Reject recharge (SUPER_ADMIN)
- `GET /api/v1/wallets/agency/{agencyId}/transactions` - Get transaction history

### Flight Search
- `POST /api/v1/flights/search` - Search flights
- `GET /api/v1/flights/offers/{offerId}` - Get offer details
- `GET /api/v1/flights/offers/{offerId}/fare-rules` - Get fare rules

### Booking Management
- `POST /api/v1/bookings` - Create booking
- `GET /api/v1/bookings/{bookingId}` - Get booking by ID
- `GET /api/v1/bookings/agency/{agencyId}` - Get agency bookings
- `POST /api/v1/bookings/{bookingId}/cancel` - Cancel booking

### Ticketing
- `POST /api/v1/tickets/issue` - Issue ticket
- `GET /api/v1/tickets/{ticketId}` - Get ticket by ID
- `GET /api/v1/tickets/agency/{agencyId}` - Get agency tickets
- `POST /api/v1/tickets/{ticketId}/void` - Void ticket
- `POST /api/v1/tickets/{ticketId}/refund` - Refund ticket

### Reporting
- `POST /api/v1/reports/transactions` - Generate transaction report
- `POST /api/v1/reports/financial` - Generate financial report
- `GET /api/v1/reports/{reportId}/export/csv` - Export report as CSV
- `GET /api/v1/reports/{reportId}/export/pdf` - Export report as PDF

### Notifications
- `GET /api/v1/notifications` - Get user notifications
- `POST /api/v1/notifications/{notificationId}/read` - Mark as read
- `PUT /api/v1/notifications/preferences` - Update preferences

### Back Office
- `GET /api/v1/backoffice/dashboard` - Get dashboard metrics (SUPER_ADMIN)
- `POST /api/v1/backoffice/wallet/adjust` - Manual wallet adjustment (SUPER_ADMIN)
- `POST /api/v1/backoffice/impersonate` - Impersonate user (SUPER_ADMIN)
- `GET /api/v1/backoffice/config` - Get system configuration (SUPER_ADMIN)
- `PUT /api/v1/backoffice/config` - Update system configuration (SUPER_ADMIN)

### Queue Management
- `GET /api/v1/queue/messages` - Get queue messages
- `POST /api/v1/queue/messages/{messageId}/process` - Process message
- `GET /api/v1/queue/messages/history` - Get message history

## Role-Based Access Control

### Roles

1. **SUPER_ADMIN**
   - Full system access
   - Manage all agencies
   - View cross-agency reports
   - System configuration

2. **AGENCY_ADMIN**
   - Manage users within own agency
   - View agency reports
   - Manage agency settings

3. **FINANCE_USER**
   - Manage wallet recharges
   - View financial reports
   - View transaction history

4. **HR_USER**
   - Manage agency users
   - View user activity

5. **AGENT**
   - Search flights
   - Create bookings
   - Issue tickets
   - View own transactions

## Response Codes

- `200 OK` - Successful request
- `201 Created` - Resource created successfully
- `400 Bad Request` - Invalid request parameters
- `401 Unauthorized` - Missing or invalid authentication
- `403 Forbidden` - Insufficient permissions
- `404 Not Found` - Resource not found
- `409 Conflict` - Resource conflict (e.g., duplicate matricule number)
- `429 Too Many Requests` - Rate limit exceeded
- `500 Internal Server Error` - Server error
- `503 Service Unavailable` - External service (Amadeus) unavailable

## Error Response Format

All error responses follow this structure:

```json
{
  "timestamp": "2024-01-19T08:15:00Z",
  "status": 400,
  "error": "Bad Request",
  "message": "Validation failed for field 'matriculeNumber': must not be blank",
  "path": "/api/v1/agencies"
}
```

## Rate Limiting

API requests are rate-limited per agency:
- Default: 100 requests per minute
- Configurable by SUPER_ADMIN
- Rate limit headers included in responses:
  - `X-RateLimit-Limit`: Maximum requests allowed
  - `X-RateLimit-Remaining`: Remaining requests
  - `X-RateLimit-Reset`: Time when limit resets

## Pagination

List endpoints support pagination:

```
GET /api/v1/bookings/agency/{agencyId}?page=0&size=20&sort=createdAt,desc
```

Parameters:
- `page`: Page number (0-indexed)
- `size`: Items per page (default: 20, max: 100)
- `sort`: Sort field and direction (e.g., `createdAt,desc`)

## Testing with Swagger UI

1. **Navigate to Swagger UI**: http://localhost:8081/swagger-ui.html
2. **Authenticate**:
   - Click "Authorize" button
   - Login via `/api/v1/auth/login` to get token
   - Enter token in format: `Bearer {token}`
   - Click "Authorize"
3. **Test Endpoints**:
   - Select an endpoint
   - Click "Try it out"
   - Fill in parameters
   - Click "Execute"
   - View response

## Generating Client SDKs

Use OpenAPI Generator to create client SDKs:

```bash
# Install OpenAPI Generator
npm install @openapitools/openapi-generator-cli -g

# Generate TypeScript client
openapi-generator-cli generate \
  -i http://localhost:8081/api-docs \
  -g typescript-axios \
  -o ./client-sdk

# Generate Java client
openapi-generator-cli generate \
  -i http://localhost:8081/api-docs \
  -g java \
  -o ./client-sdk
```

## Importing to Postman

1. Open Postman
2. Click "Import"
3. Enter URL: `http://localhost:8081/api-docs`
4. Click "Import"
5. Collection will be created with all endpoints

## Additional Resources

- [OpenAPI Specification](https://swagger.io/specification/)
- [Swagger UI Documentation](https://swagger.io/tools/swagger-ui/)
- [OpenAPI Generator](https://openapi-generator.tech/)
- [Spring Boot Actuator Endpoints](http://localhost:8081/actuator)

## Support

For API support or questions:
- Email: support@b2bflight.com
- Documentation: http://localhost:8081/swagger-ui.html
