# Tenant API - Complete Backend Documentation

## 📋 Overview

Comprehensive REST API for managing platform tenants. All endpoints require JWT authentication and follow RESTful conventions.

**Base URL**: `http://localhost:8000/api/tenants`

**Authentication**: JWT Bearer Token

---

## 🔐 Authentication

All requests must include the JWT token in the Authorization header:

```
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

If token is missing or invalid, you'll receive:
```json
{
  "message": "Unauthenticated"
}
```
Status: **401 Unauthorized**

---

## 📚 API Endpoints

### 1. GET /api/tenants - List All Tenants

Retrieve a paginated list of tenants with optional filtering and searching.

**Request**:
```
GET /api/tenants?page=1&per_page=10&search=tech&status=active
Authorization: Bearer {token}
```

**Query Parameters**:
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| page | integer | 1 | Page number for pagination |
| per_page | integer | 10 | Items per page (1-100) |
| search | string | "" | Search by name or slug |
| status | string | null | Filter by status (active/inactive/suspended) |

**Response** (200 OK):
```json
{
  "success": true,
  "message": "Tenants retrieved successfully",
  "data": [
    {
      "id": 1,
      "name": "TechCorp Solutions",
      "slug": "techcorp-solutions",
      "description": "Enterprise technology company",
      "logo_url": "https://example.com/logo.png",
      "website_url": "https://techcorp.com",
      "support_email": "support@techcorp.com",
      "support_phone": "+1-800-000-0000",
      "status": "active",
      "subscription_plan": "enterprise",
      "subscription_status": "active",
      "subscription_end_date": "2025-01-27",
      "is_white_label": true,
      "theme_color": "#007bff",
      "custom_domain": "custom.techcorp.com",
      "api_limit_per_hour": 50000,
      "max_users": 1000,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2025-01-27T15:45:00Z"
    }
  ],
  "pagination": {
    "current_page": 1,
    "total": 25,
    "per_page": 10,
    "last_page": 3
  }
}
```

---

### 2. POST /api/tenants - Create New Tenant

Create a new tenant with configuration and settings.

**Request**:
```
POST /api/tenants
Authorization: Bearer {token}
Content-Type: application/json

{
  "name": "TechCorp Solutions",
  "slug": "techcorp-solutions",
  "description": "Enterprise technology company",
  "status": "active",
  "subscription_plan": "enterprise",
  "support_email": "support@techcorp.com",
  "support_phone": "+1-800-000-0000",
  "website_url": "https://techcorp.com",
  "logo_url": "https://example.com/logo.png",
  "custom_domain": "custom.techcorp.com",
  "theme_color": "#007bff",
  "is_white_label": true,
  "api_limit_per_hour": 50000,
  "max_users": 1000
}
```

**Request Body Parameters**:

| Field | Type | Required | Validation | Description |
|-------|------|----------|-----------|-------------|
| name | string | ✅ | min:3, max:255, unique | Tenant name |
| slug | string | ❌ | min:3, max:255, unique | URL slug (auto-generated if not provided) |
| description | string | ❌ | max:1000 | Company description |
| status | string | ✅ | in:active,inactive,suspended | Tenant status |
| subscription_plan | string | ✅ | in:starter,professional,enterprise,custom | Subscription tier |
| support_email | string | ❌ | email | Support contact email |
| support_phone | string | ❌ | max:20 | Support contact phone |
| website_url | string | ❌ | url | Company website |
| logo_url | string | ❌ | url | Logo image URL |
| custom_domain | string | ❌ | unique | Custom domain for tenant |
| theme_color | string | ❌ | regex:#[0-9A-Fa-f]{6} | Hex color for theme |
| is_white_label | boolean | ❌ | default:false | Enable white-label features |
| api_limit_per_hour | integer | ❌ | min:100, max:100000, default:1000 | API rate limit |
| max_users | integer | ❌ | min:1, max:10000, default:100 | Maximum concurrent users |

**Success Response** (201 Created):
```json
{
  "success": true,
  "message": "Tenant created successfully",
  "data": {
    "id": 1,
    "name": "TechCorp Solutions",
    "slug": "techcorp-solutions",
    "status": "active",
    "subscription_plan": "enterprise",
    "created_at": "2025-01-27T15:45:00Z"
  }
}
```

**Validation Error** (422 Unprocessable Entity):
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "name": [
      "The name has already been taken.",
      "The name must be at least 3 characters."
    ],
    "subscription_plan": [
      "The selected subscription_plan is invalid."
    ]
  }
}
```

**Server Error** (500 Internal Server Error):
```json
{
  "success": false,
  "message": "Error creating tenant: [error details]"
}
```

---

### 3. GET /api/tenants/{id} - Get Single Tenant

Retrieve detailed information about a specific tenant.

**Request**:
```
GET /api/tenants/1
Authorization: Bearer {token}
```

**URL Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| id | integer | Tenant ID |

**Response** (200 OK):
```json
{
  "success": true,
  "message": "Tenant retrieved successfully",
  "data": {
    "id": 1,
    "name": "TechCorp Solutions",
    "slug": "techcorp-solutions",
    "description": "Enterprise technology company",
    "logo_url": "https://example.com/logo.png",
    "website_url": "https://techcorp.com",
    "support_email": "support@techcorp.com",
    "support_phone": "+1-800-000-0000",
    "status": "active",
    "subscription_plan": "enterprise",
    "subscription_status": "active",
    "subscription_end_date": "2025-01-27",
    "is_white_label": true,
    "theme_color": "#007bff",
    "custom_domain": "custom.techcorp.com",
    "api_limit_per_hour": 50000,
    "max_users": 1000,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2025-01-27T15:45:00Z",
    "settings": {
      "id": 1,
      "tenant_id": 1,
      "key": "notification_settings",
      "value": {
        "email_notifications": true,
        "sms_notifications": false,
        "in_app_notifications": true
      },
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    },
    "user_count": 250,
    "operator_count": 15,
    "driver_count": 450
  }
}
```

**Not Found Error** (404 Not Found):
```json
{
  "message": "No query results found for model [App\\Models\\Tenant] 1"
}
```

---

### 4. PUT /api/tenants/{id} - Update Tenant

Update an existing tenant's information.

**Request**:
```
PUT /api/tenants/1
Authorization: Bearer {token}
Content-Type: application/json

{
  "status": "suspended",
  "support_email": "newsupport@techcorp.com",
  "api_limit_per_hour": 75000
}
```

**Request Body Parameters**:
All parameters from POST are optional for PUT (only update what you need).

**Response** (200 OK):
```json
{
  "success": true,
  "message": "Tenant updated successfully",
  "data": {
    "id": 1,
    "name": "TechCorp Solutions",
    "status": "suspended",
    "support_email": "newsupport@techcorp.com",
    "api_limit_per_hour": 75000,
    ...
  }
}
```

**Validation Error** (422):
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "status": [
      "The selected status is invalid."
    ]
  }
}
```

---

### 5. DELETE /api/tenants/{id} - Delete Tenant

Soft delete a tenant (data preserved, record marked deleted).

**Request**:
```
DELETE /api/tenants/1
Authorization: Bearer {token}
```

**Response** (200 OK):
```json
{
  "success": true,
  "message": "Tenant 'TechCorp Solutions' deleted successfully"
}
```

**Not Found Error** (404):
```json
{
  "message": "No query results found for model [App\\Models\\Tenant] 1"
}
```

---

### 6. GET /api/tenants/{id}/statistics - Get Tenant Statistics

Retrieve usage statistics and metrics for a tenant.

**Request**:
```
GET /api/tenants/1/statistics
Authorization: Bearer {token}
```

**Response** (200 OK):
```json
{
  "success": true,
  "data": {
    "total_users": 250,
    "total_operators": 15,
    "total_drivers": 450,
    "total_passengers": 2800,
    "total_vehicles": 520,
    "total_bookings": 45670,
    "total_payments": 25000000
  }
}
```

---

### 7. GET /api/tenants/validate-slug - Validate Slug Availability

Check if a slug is available for use.

**Request**:
```
GET /api/tenants/validate-slug?slug=my-tenant-name
Authorization: Bearer {token}
```

**Query Parameters**:
| Parameter | Type | Description |
|-----------|------|-------------|
| slug | string | Slug to validate |

**Response - Available** (200 OK):
```json
{
  "success": true,
  "available": true,
  "slug": "my-tenant-name"
}
```

**Response - Not Available** (200 OK):
```json
{
  "success": true,
  "available": false,
  "slug": "my-tenant-name"
}
```

**Response - Invalid Slug** (200 OK):
```json
{
  "success": false,
  "available": false,
  "message": "Invalid slug"
}
```

---

## 📊 Status Codes Reference

| Code | Meaning | When Used |
|------|---------|-----------|
| 200 | OK | Successful GET, PUT, DELETE |
| 201 | Created | Successful POST (resource created) |
| 400 | Bad Request | Malformed request |
| 401 | Unauthorized | Missing or invalid JWT token |
| 404 | Not Found | Tenant ID doesn't exist |
| 422 | Unprocessable Entity | Validation failed |
| 500 | Internal Server Error | Server error |

---

## 🔍 Usage Examples

### Example 1: Create a Starter Plan Tenant

```bash
curl -X POST http://localhost:8000/api/tenants \
  -H "Authorization: Bearer eyJhbGc..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Small Business Inc",
    "status": "active",
    "subscription_plan": "starter",
    "support_email": "support@smallbiz.com",
    "api_limit_per_hour": 1000,
    "max_users": 50
  }'
```

### Example 2: List Active Tenants with Pagination

```bash
curl -X GET "http://localhost:8000/api/tenants?page=1&per_page=20&status=active" \
  -H "Authorization: Bearer eyJhbGc..."
```

### Example 3: Search for Tenants

```bash
curl -X GET "http://localhost:8000/api/tenants?search=tech&per_page=10" \
  -H "Authorization: Bearer eyJhbGc..."
```

### Example 4: Update Tenant Status

```bash
curl -X PUT http://localhost:8000/api/tenants/1 \
  -H "Authorization: Bearer eyJhbGc..." \
  -H "Content-Type: application/json" \
  -d '{
    "status": "suspended",
    "api_limit_per_hour": 0
  }'
```

### Example 5: Get Tenant Statistics

```bash
curl -X GET http://localhost:8000/api/tenants/1/statistics \
  -H "Authorization: Bearer eyJhbGc..."
```

---

## 🎯 Tenant Model Properties

```
Tenant {
  id: number              // Primary key
  name: string            // Tenant name (required, unique)
  slug: string            // URL-friendly identifier (unique)
  description: string     // Optional description
  logo_url: string        // Company logo URL
  website_url: string     // Company website
  support_email: string   // Support contact email
  support_phone: string   // Support contact phone
  status: enum            // active|inactive|suspended
  subscription_plan: enum // starter|professional|enterprise|custom
  subscription_status: enum // active|expired|suspended
  subscription_end_date: date // When subscription expires
  is_white_label: bool    // White-label feature enabled
  theme_color: string     // Hex color for UI theme
  custom_domain: string   // Custom domain for tenant
  api_limit_per_hour: int // API rate limit
  max_users: int          // Maximum concurrent users
  created_at: datetime    // Record creation timestamp
  updated_at: datetime    // Last update timestamp
  deleted_at: datetime    // Soft delete timestamp (null if active)
}
```

---

## 🔐 Access Control

- **Authentication Required**: YES (JWT token)
- **Authorization Level**: Admin/Platform Admin
- **Rate Limit**: Standard API rate limits apply
- **Soft Deletes**: Enabled (deleted records not shown)

---

## 📝 Field Validation Rules

```php
'name' => 'required|string|min:3|max:255|unique:tenants,name'
'slug' => 'nullable|string|min:3|max:255|unique:tenants,slug'
'description' => 'nullable|string|max:1000'
'logo_url' => 'nullable|url'
'website_url' => 'nullable|url'
'support_email' => 'nullable|email'
'support_phone' => 'nullable|string|max:20'
'status' => 'required|in:active,inactive,suspended'
'subscription_plan' => 'required|in:starter,professional,enterprise,custom'
'subscription_status' => 'in:active,expired,suspended'
'subscription_end_date' => 'nullable|date'
'is_white_label' => 'nullable|boolean'
'theme_color' => 'nullable|string|regex:/^#[0-9A-Fa-f]{6}$/'
'custom_domain' => 'nullable|string|unique:tenants,custom_domain'
'api_limit_per_hour' => 'nullable|integer|min:100|max:100000'
'max_users' => 'nullable|integer|min:1|max:10000'
```

---

## 🔄 Response Format

All API responses follow this format:

**Success**:
```json
{
  "success": true,
  "message": "Description of success",
  "data": { ... },
  "pagination": { ... }  // Only for list endpoints
}
```

**Error**:
```json
{
  "success": false,
  "message": "Error description",
  "errors": { ... }  // Only for validation errors
}
```

---

## 💡 Best Practices

1. **Always include Authorization header** - All requests require JWT token
2. **Handle pagination** - Use per_page and page parameters for large datasets
3. **Use filtering** - Filter by status to reduce response size
4. **Validate locally first** - Use slug validation before form submission
5. **Handle errors gracefully** - Check success flag and display appropriate messages
6. **Rate limit awareness** - Respect API limits set in subscription plan
7. **Use HTTPS** - Always use HTTPS in production
8. **Cache responses** - Cache tenant lists locally when possible

---

## 🚨 Common Errors and Solutions

| Error | Cause | Solution |
|-------|-------|----------|
| 401 Unauthorized | Missing JWT token | Add Authorization header with valid token |
| 404 Not Found | Tenant ID doesn't exist | Verify tenant ID exists in database |
| 422 Validation Failed | Invalid input data | Check field validation rules |
| 409 Conflict | Name/slug already exists | Use different name or auto-generated slug |
| 422 Invalid email | Malformed email | Use valid email format |
| 422 Invalid URL | Malformed URL | Start with http:// or https:// |

---

## 📞 Support

For API issues:
1. Check authentication (JWT token validity)
2. Verify request format (JSON, headers)
3. Check server logs: `storage/logs/laravel.log`
4. Review validation errors in response
5. Contact development team with request details

---

*API Documentation v1.0*
*Last Updated: January 27, 2026*
