# API Layer

## Overview

The Building Management System exposes a RESTful API following industry best practices. All endpoints are versioned and follow consistent conventions.

## API Conventions

### Base URL

```
Production:  https://api.example.com/api/v1
Development: http://127.0.0.1:8001/api/v1
```

### Versioning

API version is included in the URL path:
- Current version: `v1`
- Future versions: `v2`, `v3`, etc.

### HTTP Methods

| Method | Usage | Example |
|--------|-------|---------|
| GET | Retrieve resource(s) | `GET /users` |
| POST | Create resource | `POST /users` |
| PUT | Full update | `PUT /users/1` |
| PATCH | Partial update | `PATCH /users/1` |
| DELETE | Remove resource | `DELETE /users/1` |

### URL Naming

```
# Resource collections (plural nouns)
GET    /api/v1/users
POST   /api/v1/users

# Individual resources
GET    /api/v1/users/{id}
PUT    /api/v1/users/{id}
DELETE /api/v1/users/{id}

# Nested resources
GET    /api/v1/users/{id}/roles
POST   /api/v1/projects/{id}/materials

# Actions (verbs for non-CRUD operations)
POST   /api/v1/users/{id}/activate
POST   /api/v1/orders/{id}/approve
```

## Request Format

### Headers

```http
Content-Type: application/json
Accept: application/json
Authorization: Bearer {token}
Accept-Language: en|ar
X-Branch-ID: {branch_id}
```

### Query Parameters

```
# Pagination
?page=1&per_page=15

# Sorting
?sort=created_at&order=desc

# Filtering
?status=active&type=employee

# Including relationships
?include=roles,department

# Selecting fields
?fields=id,name,email
```

### Request Body

```json
{
    "name": "John Doe",
    "email": "john@example.com",
    "role_id": 1,
    "metadata": {
        "department": "Engineering"
    }
}
```

## Response Format

### Standard Response Structure

All API responses follow this structure:

```json
{
    "success": true,
    "code": 200,
    "message": "Request processed successfully",
    "data": { ... }
}
```

### Success Responses

**Single Resource (200 OK)**
```json
{
    "success": true,
    "code": 200,
    "message": "User retrieved successfully",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "created_at": "2026-02-08T10:30:00.000Z"
    }
}
```

**Resource Collection (200 OK)**
```json
{
    "success": true,
    "code": 200,
    "message": "Users retrieved successfully",
    "data": [
        { "id": 1, "name": "John Doe" },
        { "id": 2, "name": "Jane Smith" }
    ],
    "meta": {
        "current_page": 1,
        "last_page": 10,
        "per_page": 15,
        "total": 150
    },
    "links": {
        "first": "/api/v1/users?page=1",
        "last": "/api/v1/users?page=10",
        "next": "/api/v1/users?page=2",
        "prev": null
    }
}
```

**Resource Created (201 Created)**
```json
{
    "success": true,
    "code": 201,
    "message": "User created successfully",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    }
}
```

**No Content (204 No Content)**
```
HTTP/1.1 204 No Content
```

### Error Responses

**Validation Error (422 Unprocessable Entity)**
```json
{
    "success": false,
    "code": 422,
    "message": "The given data was invalid",
    "errors": {
        "email": ["The email field is required."],
        "name": ["The name must be at least 2 characters."]
    }
}
```

**Authentication Error (401 Unauthorized)**
```json
{
    "success": false,
    "code": 401,
    "message": "Unauthenticated"
}
```

**Authorization Error (403 Forbidden)**
```json
{
    "success": false,
    "code": 403,
    "message": "You do not have permission to perform this action"
}
```

**Not Found (404 Not Found)**
```json
{
    "success": false,
    "code": 404,
    "message": "Resource not found"
}
```

**Server Error (500 Internal Server Error)**
```json
{
    "success": false,
    "code": 500,
    "message": "An unexpected error occurred"
}
```

## Authentication

### Token-Based Authentication (Sanctum)

**Login**
```http
POST /api/v1/auth/login
Content-Type: application/json

{
    "email": "user@example.com",
    "password": "password"
}
```

**Response**
```json
{
    "success": true,
    "data": {
        "token": "1|abc123...",
        "user": {
            "id": 1,
            "name": "John Doe"
        }
    }
}
```

**Using Token**
```http
GET /api/v1/users
Authorization: Bearer 1|abc123...
```

### Magic Link Authentication

```http
POST /api/v1/auth/magic-login/{type}/{slug}
```

Types: `driver`, `supplier`

## Route Organization

Routes are organized by domain in `routes/apis/`:

```
routes/apis/
├── api.php              # Main entry point
├── user.php             # Authenticated user routes
├── construction.php     # Construction domain
├── accounting.php       # Accounting domain
├── management.php       # Management domain
├── procurement.php      # Procurement domain
├── core.php             # Core functionality
├── crm.php              # CRM domain
├── Maintenance/         # Maintenance domain
├── ProductsCatalog/     # Catalog domain
└── Supply/              # Supply domain
```

### Route Definition Example

```php
// routes/apis/management.php

Route::prefix('management')->group(function () {

    Route::prefix('employees')->group(function () {
        Route::get('/', [EmployeeController::class, 'index']);
        Route::post('/', [EmployeeController::class, 'store']);
        Route::get('/{employee}', [EmployeeController::class, 'show']);
        Route::put('/{employee}', [EmployeeController::class, 'update']);
        Route::delete('/{employee}', [EmployeeController::class, 'destroy']);

        // Custom actions
        Route::post('/{employee}/terminate', [EmployeeController::class, 'terminate']);
    });

});
```

## Controller Structure

```php
namespace App\Http\Controllers\V1\Management;

class EmployeeController extends Controller
{
    public function __construct(
        private EmployeeService $service
    ) {}

    public function index(IndexEmployeeRequest $request): JsonResponse
    {
        $employees = $this->service->list($request->validated());

        return response()->json([
            'success' => true,
            'data' => EmployeeResource::collection($employees),
            'meta' => $this->paginationMeta($employees)
        ]);
    }

    public function store(StoreEmployeeRequest $request): JsonResponse
    {
        $employee = $this->service->create(
            EmployeeDTO::fromRequest($request)
        );

        return response()->json([
            'success' => true,
            'code' => 201,
            'message' => 'Employee created successfully',
            'data' => new EmployeeResource($employee)
        ], 201);
    }

    public function show(Employee $employee): JsonResponse
    {
        $this->authorize('view', $employee);

        return response()->json([
            'success' => true,
            'data' => new EmployeeResource($employee->load('department', 'role'))
        ]);
    }
}
```

## Rate Limiting

API requests are rate-limited per user:

| Endpoint Type | Limit | Window |
|--------------|-------|--------|
| General API | 60 requests | 1 minute |
| Authentication | 5 requests | 1 minute |
| File Upload | 10 requests | 1 minute |

Rate limit headers:
```http
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
X-RateLimit-Reset: 1707391800
```

## API Endpoints by Domain

### Core

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/auth/login` | POST | User login |
| `/auth/logout` | POST | User logout |
| `/auth/me` | GET | Current user |
| `/branches` | GET | List branches |
| `/settings` | GET | System settings |

### Management

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/management/employees` | GET, POST | Employee list/create |
| `/management/employees/{id}` | GET, PUT, DELETE | Employee CRUD |
| `/management/attendance` | GET, POST | Attendance records |
| `/management/payroll-runs` | GET, POST | Payroll processing |
| `/management/leaves` | GET, POST | Leave requests |

### Accounting

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/accounting/invoices` | GET, POST | Invoices |
| `/accounting/payments` | GET, POST | Payments |
| `/accounting/accounts` | GET | Chart of accounts |
| `/accounting/reports/*` | GET | Financial reports |

### Construction

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/construction/projects` | GET, POST | Projects |
| `/construction/estimates` | GET, POST | Cost estimates |
| `/construction/materials` | GET, POST | Material tracking |

### Maintenance

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/maintenance/assets` | GET, POST | Assets |
| `/maintenance/visits` | GET, POST | Service visits |
| `/maintenance/checklists` | GET, POST | Inspection checklists |
| `/maintenance/contracts` | GET, POST | Service contracts |
