# Ampeco API Controller

This document provides comprehensive information about the AmpecoApiController in the Frontend module, which handles all interactions with the Ampeco EV charging platform API.

## Overview

The `AmpecoApiController` is a Laravel controller that provides a clean, simple interface to interact with the Ampeco API. It handles:

-   **Tariff Management**: Get pricing information
-   **User Management**: User balance, custom fees
-   **Charging Sessions**: Start/stop EVSE sessions
-   **Session Monitoring**: Get session information
-   **Notifications**: Send notifications to users

## Features

✅ **Simple & Clean Code**: Easy to read and maintain
✅ **Comprehensive Error Handling**: Graceful error responses
✅ **Request Validation**: Input validation for all endpoints
✅ **Consistent Response Format**: Standardized JSON responses
✅ **Logging**: Error logging for debugging
✅ **Fully Tested**: Complete test coverage

## API Endpoints

### Tariff Management

#### Get Tariff Information

```http
GET /api/ampeco/tariffs/{tariffId}
```

**Example Response:**

```json
{
    "success": true,
    "status_code": 200,
    "data": {
        "id": 71,
        "name": "Standard Tariff",
        "pricing": {
            "pricePerKwh": 5.5
        }
    }
}
```

### User Management

#### Get User Information

```http
GET /api/ampeco/users/{userId}
```

#### Add User Balance

```http
POST /api/ampeco/users/add-balance
```

**Request Body:**

```json
{
    "user_id": 123,
    "amount": 50.0,
    "currency": "THB"
}
```

#### Apply Custom Fee

```http
POST /api/ampeco/users/{userId}/apply-custom-fee
```

**Request Body:**

```json
{
    "fee_amount": 10.0,
    "fee_type": "service",
    "description": "Service fee"
}
```

### EVSE Management

#### Start Charging Session

```http
POST /api/ampeco/evse/{evseId}/start
```

**Request Body:**

```json
{
    "user_id": 123,
    "connector_id": 1,
    "tariff_id": 71
}
```

### Session Management

#### Get Session Information

```http
GET /api/ampeco/sessions/{sessionId}
```

#### Stop Charging Session

```http
POST /api/ampeco/charge-points/{chargePointId}/stop/{sessionId}
```

### Notifications

#### Send Notification

```http
POST /api/ampeco/notifications
```

**Request Body:**

```json
{
    "type": "info",
    "message": "Your charging session has started",
    "user_id": 123
}
```

## Response Format

All endpoints return a consistent JSON response format:

### Success Response

```json
{
    "success": true,
    "status_code": 200,
    "data": {
        // Response data from Ampeco API
    }
}
```

### Error Response

```json
{
    "success": false,
    "message": "Error description",
    "error": {
        // Error details from Ampeco API or exception message
    }
}
```

## Configuration

The controller uses the following configuration:

```php
private string $baseUrl = 'https://cp.evconnex-th.com/public-api';
private string $bearerToken = '8714b9ff-6386-44ce-9742-cf48b57e1052';
```

**Note**: In production, the bearer token should be moved to environment variables for security.

## Testing

### Running Unit Tests

Execute the comprehensive PHPUnit tests:

```bash
# Run all Frontend module tests
php artisan test Modules/Frontend/tests/Feature/AmpecoApiControllerTest.php

# Run specific test method
php artisan test --filter test_get_tariff_success
```

### Manual Testing

Use the provided test runner script:

```bash
# From the Frontend module directory
php test-ampeco-api.php
```

This will run manual tests against the actual Ampeco API endpoints.

### Test Coverage

The test suite covers:

-   ✅ Successful API responses
-   ✅ Error handling and exceptions
-   ✅ Request validation
-   ✅ HTTP status codes
-   ✅ Response format consistency
-   ✅ Mock HTTP client testing

## Usage Examples

### Basic Usage in Controller

```php
use Modules\Frontend\app\Http\Controllers\AmpecoApiController;

class MyController extends Controller
{
    public function getTariffPrice(int $tariffId)
    {
        $ampecoApi = new AmpecoApiController();
        $response = $ampecoApi->getTariff($tariffId);

        $data = json_decode($response->getContent(), true);

        if ($data['success']) {
            $price = $data['data']['pricing']['pricePerKwh'];
            return "Price: {$price} THB/kWh";
        }

        return "Error: " . $data['message'];
    }
}
```

### Usage in Views/Frontend

```javascript
// Example AJAX call to get tariff
fetch("/api/ampeco/tariffs/71")
    .then((response) => response.json())
    .then((data) => {
        if (data.success) {
            console.log("Tariff price:", data.data.pricing.pricePerKwh);
        } else {
            console.error("Error:", data.message);
        }
    });
```

## Error Handling

The controller provides comprehensive error handling:

1. **Network Errors**: Handles connection timeouts and network issues
2. **API Errors**: Processes error responses from Ampeco API
3. **Validation Errors**: Returns validation error messages for invalid input
4. **Server Errors**: Handles unexpected server errors gracefully

All errors are logged using Laravel's logging system for debugging purposes.

## Security Considerations

1. **Authentication**: API calls are authenticated using Bearer token
2. **Input Validation**: All user inputs are validated before sending to API
3. **Error Information**: Sensitive error details are not exposed to client
4. **Logging**: Errors are logged securely for monitoring

## Dependencies

-   **GuzzleHttp**: HTTP client for API requests
-   **Laravel Validation**: Request validation
-   **Laravel Logging**: Error logging

## Files Structure

```
Modules/Frontend/
├── app/Http/Controllers/
│   ├── AmpecoApiController.php          # Main controller
│   └── api.php                          # Original API examples
├── routes/
│   └── api.php                          # API routes
├── tests/Feature/
│   └── AmpecoApiControllerTest.php      # Unit tests
├── test-ampeco-api.php                  # Manual test runner
└── AMPECO_API_README.md                 # This documentation
```

## Changelog

### Version 1.0.0

-   ✅ Initial implementation of AmpecoApiController
-   ✅ All Ampeco API endpoints implemented
-   ✅ Comprehensive error handling
-   ✅ Request validation
-   ✅ Unit tests with full coverage
-   ✅ Manual test runner
-   ✅ API routes configuration
-   ✅ Documentation

## Contributing

When contributing to this controller:

1. Maintain the consistent response format
2. Add appropriate request validation
3. Include comprehensive error handling
4. Write unit tests for new methods
5. Update this documentation

## Support

For issues or questions related to the AmpecoApiController, please check:

1. Laravel logs for error details
2. Ampeco API documentation: https://developers.ampeco.com/
3. Test results for debugging information
