# Payment Service API Documentation

## Base URL
```
https://your-domain.com/api/v1
```

## Authentication
All protected endpoints require JWT authentication via the `Authorization` header:
```
Authorization: Bearer <jwt_token>
```

## Error Responses
All error responses follow this format:
```json
{
  "error": "Error message description",
  "code": "ERROR_CODE",
  "details": {}
}
```

## Client Management

### Register Client
Register a new client in the system.

**Endpoint:** `POST /clients/register`

**Request Body:**
```json
{
  "name": "Acme Corporation",
  "email": "admin@acme.com",
  "phone": "254712345678",
  "address": "Nairobi, Kenya",
  "username": "acme_admin",
  "password": "secure_password123"
}
```

**Response:**
```json
{
  "message": "Client registered successfully",
  "client": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Acme Corporation",
    "email": "admin@acme.com",
    "phone": "254712345678",
    "address": "Nairobi, Kenya",
    "username": "acme_admin",
    "status": "active",
    "is_active": true,
    "last_login": null,
    "created_at": "2024-01-01T00:00:00Z",
    "updated_at": "2024-01-01T00:00:00Z"
  }
}
```

### Login Client
Authenticate a client and receive a JWT token.

**Endpoint:** `POST /clients/login`

**Request Body:**
```json
{
  "username": "acme_admin",
  "password": "secure_password123"
}
```

**Response:**
```json
{
  "message": "Login successful",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "client": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Acme Corporation",
    "email": "admin@acme.com",
    "username": "acme_admin",
    "status": "active",
    "is_active": true,
    "last_login": "2024-01-01T00:00:00Z",
    "created_at": "2024-01-01T00:00:00Z",
    "updated_at": "2024-01-01T00:00:00Z"
  }
}
```

### Set Payment Credentials
Configure M-Pesa credentials for a client.

**Endpoint:** `POST /clients/credentials`

**Headers:** `Authorization: Bearer <token>`

**Request Body:**
```json
{
  "provider": "mpesa",
  "consumer_key": "your_consumer_key",
  "consumer_secret": "your_consumer_secret",
  "short_code": "174379",
  "pass_key": "your_pass_key",
  "base_url": "https://sandbox.safaricom.co.ke",
  "callback_url": "https://your-domain.com/api/v1/callbacks/mpesa",
  "is_active": true
}
```

**Response:**
```json
{
  "message": "Payment credentials set successfully"
}
```

### Get Payment Credentials
Retrieve payment credentials for a client.

**Endpoint:** `GET /clients/credentials`

**Headers:** `Authorization: Bearer <token>`

**Query Parameters:**
- `provider` (optional): Filter by payment provider

**Response:**
```json
{
  "credentials": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440001",
      "client_id": "550e8400-e29b-41d4-a716-446655440000",
      "provider": "mpesa",
      "consumer_key": "your_consumer_key",
      "short_code": "174379",
      "base_url": "https://sandbox.safaricom.co.ke",
      "callback_url": "https://your-domain.com/api/v1/callbacks/mpesa",
      "is_active": true,
      "created_at": "2024-01-01T00:00:00Z",
      "updated_at": "2024-01-01T00:00:00Z"
    }
  ]
}
```

## Package Management

### Create Package
Create a new internet package for a client.

**Endpoint:** `POST /packages`

**Headers:** `Authorization: Bearer <token>`

**Request Body:**
```json
{
  "name": "Basic Internet Plan",
  "description": "10Mbps unlimited internet for 1 month",
  "amount": 100.00,
  "currency": "KES",
  "speed": "10Mbps",
  "duration": "1 month"
}
```

**Response:**
```json
{
  "message": "Package created successfully",
  "data": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "client_id": "550e8400-e29b-41d4-a716-446655440001",
    "name": "Basic Internet Plan",
    "description": "10Mbps unlimited internet for 1 month",
    "amount": 100.00,
    "currency": "KES",
    "speed": "10Mbps",
    "duration": "1 month",
    "is_active": true,
    "created_at": "2025-01-01T12:00:00Z",
    "updated_at": "2025-01-01T12:00:00Z"
  }
}
```

### Get Packages (Public)
Retrieve active packages for a client. **No authentication required**.

**Endpoint:** `GET /packages/public?client_id=<client_id>`

**Query Parameters:**
- `client_id` (required): Client UUID

**Response:**
```json
{
  "message": "Packages retrieved successfully",
  "data": [
    {
      "id": "123e4567-e89b-12d3-a456-426614174000",
      "client_id": "550e8400-e29b-41d4-a716-446655440001",
      "name": "Basic Internet Plan",
      "description": "10Mbps unlimited internet for 1 month",
      "amount": 100.00,
      "currency": "KES",
      "speed": "10Mbps",
      "duration": "1 month",
      "is_active": true,
      "created_at": "2025-01-01T12:00:00Z",
      "updated_at": "2025-01-01T12:00:00Z"
    }
  ],
  "count": 1
}
```

### Get Packages (Protected)
Retrieve all packages for a client (including inactive ones).

**Endpoint:** `GET /packages`

**Headers:** `Authorization: Bearer <token>`

**Query Parameters:**
- `active_only` (optional): If true, only return active packages (default: false)

**Response:** Same as public endpoint but may include inactive packages.

### Update Package
Update an existing internet package.

**Endpoint:** `PUT /packages/:id`

**Headers:** `Authorization: Bearer <token>`

**Request Body:**
```json
{
  "name": "Updated Internet Plan",
  "amount": 150.00,
  "is_active": false
}
```

**Response:**
```json
{
  "message": "Package updated successfully",
  "data": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "client_id": "550e8400-e29b-41d4-a716-446655440001",
    "name": "Updated Internet Plan",
    "description": "10Mbps unlimited internet for 1 month",
    "amount": 150.00,
    "currency": "KES",
    "speed": "10Mbps",
    "duration": "1 month",
    "is_active": false,
    "created_at": "2025-01-01T12:00:00Z",
    "updated_at": "2025-01-01T12:30:00Z"
  }
}
```

### Delete Package
Delete an internet package.

**Endpoint:** `DELETE /packages/:id`

**Headers:** `Authorization: Bearer <token>`

**Response:**
```json
{
  "message": "Package deleted successfully"
}
```

## Payment Processing

### Initiate Payment (Public)
Initiate a payment using M-Pesa STK Push. **No authentication required** - customers can initiate payments directly.

**Endpoint:** `POST /api/v1/payments/initiate`

**Request Body:**
```json
{
  "client_id": "550e8400-e29b-41d4-a716-446655440001",
  "phone_number": "254712345678",
  "package_id": "123e4567-e89b-12d3-a456-426614174000",
  "metadata": {
    "customer_id": "cust_456"
  }
}
```

**Response:**
```json
{
  "transaction_id": "550e8400-e29b-41d4-a716-446655440002",
  "checkout_id": "ws_CO_123456789",
  "message": "Payment initiated successfully",
  "status": "pending",
  "amount": 100.00,
  "reference": "BASIC-INT-20250110120000-AbC123",
  "phone_number": "254712345678",
  "created_at": "2025-01-01T12:00:00Z",
  "updated_at": "2025-01-01T12:00:00Z"
}
```

### Check Payment Status (Public)
Check the status of a payment transaction. **No authentication required** - customers can check payment status directly.

**Endpoint:** `POST /api/v1/payments/status`

**Request Body:**
```json
{
  "client_id": "550e8400-e29b-41d4-a716-446655440001",
  "checkout_id": "ws_CO_123456789"
}
```

**Response:**
```json
{
  "transaction_id": "550e8400-e29b-41d4-a716-446655440002",
  "checkout_id": "ws_CO_123456789",
  "status": "completed",
  "amount": 100.00,
  "reference": "INV-001",
  "phone_number": "254712345678",
  "created_at": "2024-01-01T00:00:00Z",
  "updated_at": "2024-01-01T00:05:00Z"
}
```

### Get Transactions
Retrieve a list of transactions for a client.

**Endpoint:** `GET /payments/transactions`

**Headers:** `Authorization: Bearer <token>`

**Query Parameters:**
- `limit` (optional): Number of transactions to return (default: 50, max: 1000)
- `offset` (optional): Number of transactions to skip (default: 0)

**Response:**
```json
{
  "transactions": [
    {
      "transaction_id": "550e8400-e29b-41d4-a716-446655440002",
      "checkout_id": "ws_CO_123456789",
      "status": "completed",
      "amount": 100.00,
      "reference": "INV-001",
      "phone_number": "254712345678",
      "created_at": "2024-01-01T00:00:00Z",
      "updated_at": "2024-01-01T00:05:00Z"
    }
  ],
  "limit": 50,
  "offset": 0,
  "count": 1
}
```

### Get Transaction
Retrieve details of a specific transaction.

**Endpoint:** `GET /payments/transactions/{id}`

**Headers:** `Authorization: Bearer <token>`

**Path Parameters:**
- `id`: Transaction UUID

**Response:**
```json
{
  "transaction_id": "550e8400-e29b-41d4-a716-446655440002",
  "client_id": "550e8400-e29b-41d4-a716-446655440000",
  "checkout_id": "ws_CO_123456789",
  "amount": 100.00,
  "currency": "KES",
  "payment_method": "mobile_money",
  "payment_status": "completed",
  "phone_number": "254712345678",
  "reference": "INV-001",
  "mpesa_receipt": "NLJ7RT61SV",
  "description": "Payment for internet plan",
  "metadata": "{\"plan_id\":\"plan_123\",\"customer_id\":\"cust_456\"}",
  "provider": "mpesa",
  "created_at": "2024-01-01T00:00:00Z",
  "updated_at": "2024-01-01T00:05:00Z"
}
```

## Callbacks

### M-Pesa Callback
Handle M-Pesa payment callbacks.

**Endpoint:** `POST /callbacks/mpesa`

**Request Body:**
```json
{
  "Body": {
    "stkCallback": {
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.",
      "CheckoutRequestID": "ws_CO_123456789",
      "CallbackMetadata": {
        "Item": [
          {
            "Name": "Amount",
            "Value": 100.00
          },
          {
            "Name": "MpesaReceiptNumber",
            "Value": "NLJ7RT61SV"
          },
          {
            "Name": "PhoneNumber",
            "Value": 254712345678
          }
        ]
      }
    }
  }
}
```

**Response:**
```json
{
  "ResultCode": 0,
  "ResultDesc": "Success"
}
```

## Health Checks

### Health Check
Check the overall health of the service.

**Endpoint:** `GET /health`

**Response:**
```json
{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00Z",
  "checks": {
    "database": {
      "status": "healthy",
      "type": "postgresql"
    },
    "redis": {
      "status": "healthy",
      "type": "redis"
    }
  },
  "version": "1.0.0",
  "service": "payment-service"
}
```

### Metrics
Get Prometheus metrics.

**Endpoint:** `GET /metrics`

**Response:** Prometheus metrics format

## Error Codes

| Code | Description |
|------|-------------|
| `INVALID_REQUEST` | Invalid request format or missing required fields |
| `UNAUTHORIZED` | Missing or invalid authentication token |
| `FORBIDDEN` | Insufficient permissions |
| `NOT_FOUND` | Resource not found |
| `CONFLICT` | Resource already exists |
| `RATE_LIMITED` | Too many requests |
| `INTERNAL_ERROR` | Internal server error |
| `SERVICE_UNAVAILABLE` | External service unavailable |

## Rate Limits

- **Authentication endpoints**: 10 requests per minute per IP
- **Payment endpoints**: 100 requests per minute per client
- **General endpoints**: 1000 requests per minute per IP

## Phone Number Format

Phone numbers should be in the format `254XXXXXXXXX` (Kenyan format):
- `254712345678` ✅ Valid
- `0712345678` ✅ Valid (will be converted)
- `+254712345678` ✅ Valid (will be converted)
- `712345678` ✅ Valid (will be converted)
